1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>Making things move</title>
5 <meta charset="gbk">
6 <script type="text/javascript" src="jquery.js"></script>
7 <script type="text/javascript">
8 $(document).ready(function() {
9 var canvas = $("#myCanvas");
10 var context = canvas.get(0).getContext("2d");
11
12 var canvasWidth = canvas.width();
13 var canvasHeight = canvas.height();
14 var playAnimation = true;
15
16 var startButton = $("#startAnimation");
17 var stopButton = $("#stopAnimation");
18 var canvas1 = $("#myCanvas1");
19 var context1 = canvas1.get(0).getContext("2d");
20 context1.arc(150,150,100,0,2*Math.PI,true);
21 context1.stroke();//填充绘制的圆
22 context1.beginPath();
23 context1.arc(300,300,100,0,2*Math.PI,true);
24 context1.strokeStyle="red";
25 context1.stroke();//填充绘制的圆
26
27 startButton.hide();
28 startButton.click(function() {
29 $(this).hide();
30 stopButton.show();
31 playAnimation = true;
32 animate();
33 });
34
35 stopButton.click(function() {
36 $(this).hide();
37 startButton.show();
38 playAnimation = false;
39 });
40
41 // Class that defines new shapes to draw
42 var Shape = function(x, y,radius,angle) {
43 this.x = x;
44 this.y = y;
45 this.radius=radius;
46 this.angle = angle;
47 };
48
49
50 var shapes = new Array();
51 shapes.push(new Shape(150, 150, 100,5));
52 shapes.push(new Shape(300, 300, 100,10));
53
54 function animate() {
55 context.clearRect(0, 0, canvasWidth, canvasHeight);
56 var shapesLength = shapes.length;
57 for (var i = 0; i < shapesLength; i++) {
58 var tmpShape = shapes[i];
59 var x = tmpShape.x+(tmpShape.radius*Math.cos(tmpShape.angle*(Math.PI/180)));
60 var y = tmpShape.y+(tmpShape.radius*Math.sin(tmpShape.angle*(Math.PI/180)));
61
62 if(i==0) tmpShape.angle += 5;
63 else tmpShape.angle += 10;
64 if (tmpShape.angle > 360) {
65 tmpShape.angle = 0;
66 };
67
68 context.fillRect(x, y, 10, 10);
69 };
70
71 if (playAnimation) {
72 setTimeout(animate, 33);
73 };
74 };
75
76 animate();
77 });
78 </script>
79 </head>
80
81 <body>
82 <div>
83 <button id="startAnimation">Start</button>
84 <button id="stopAnimation">Stop</button>
85 </div>
86 <canvas id="myCanvas" width="800" height="500" style="z-index:2;position:absolute"></canvas>
87 <canvas id="myCanvas1" width="800" height="500" style="z-index:1;position:absolute"></canvas>
88
89 </body>
90 </html>