首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

使用 HTML5 canvas 绘制精美的图形(5)

使用 HTML5 canvas 绘制精美的图形(5)

动画JavaScript 打包了一个强大的编程利器。这种语言能够执行很多操控,如  所示。这个代码重复运行,在 canvas 上绘制一些线条。线条颜色随机设置。
清单 8. 使用 JavaScript 创建动画
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Canvas Demo</title>
<!--[if IE]>
  <script type="text/javascript" src="excanvas.js"></script>
<![endif]-->
</head>
<body>
<div style="margin-left:30px;">
<canvas id="myCanvasTag" width="400" height="400" style="border: 10px blue solid">
</canvas>
<br /><br />
<a href="index.html">back</a>
</div>
<script>
  var mycanvas  = document.getElementById("myCanvasTag")
  var mycontext = mycanvas.getContext('2d');
  var x;
  var y;
  var x2;
  var y2;
  var r;
  var g;
  var b;
function line() {
   x=Math.floor(Math.random()*190) + Math.floor(Math.random()*190);
   y=Math.floor(Math.random()*190) + Math.floor(Math.random()*190);
   x2=Math.floor(Math.random()*190) + Math.floor(Math.random()*190);
   y2=Math.floor(Math.random()*190) + Math.floor(Math.random()*190);
   r=Math.floor(Math.random()*255);
   g=Math.floor(Math.random()*255);
   b=Math.floor(Math.random()*255);
   mycontext.moveTo(x, y);
   mycontext.lineTo(x2, y2);
   mycontext.strokeStyle='rgb(' + r + ',' + g +  ',' + b + ')';  
   mycontext.lineWidth=Math.floor(Math.random()*6);      
   mycontext.stroke();
   mycontext.restore();
}
setInterval(line, 100);

</script>
</body>
</html>




显示了这个动画的一张快照。 中的代码与本文其他所有代码示例都不同,因为 JavaScript 块被放置到页面底部,canvas 元素下方。这确保 canvas 在代码运行之前就已经被呈现了。
图 8. JavaScript 用于绘制无穷无尽的随机线条
返回列表