1 <!doctype html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>canvasTest</title>
6 </head>
7
8 <body>
9 <input type="button" id="clbtn" value="清除画布" style="border:1px solid #444;display:block;margin: 10px auto;" />
10 <canvas id="canvas" style="border:1px solid #444;display:block;margin: 10px auto;"></canvas>
11 </body>
12 <script>
13 window.onload=function(){
14 var clbtn=document.getElementById("clbtn");
15 var canvas=document.getElementById("canvas");
16 var cxt=canvas.getContext("2d");
17 canvas.width=1000;
18 canvas.height=500;
19 function ball(x,y,vx,colorindex){
20 this.x=x;
21 this.y=y;
22 this.r=22;
23 this.g=2;
24 this.vx=vx;
25 this.vy=-20;
26 this.colorindex=colorindex;
27 this.color=['red','blue','green','orange','yellow','pink'];
28 };
29 var balls=[];
30
31 // context.arc(centerx,centery,radius,startingAngle,endingAngle,anticlockwise=flase)
32 // 圆心坐标 ,半径值 ,开始角度 ,结束角度, 顺逆时针(默认flase顺时针)
33 canvas.onmousedown=function(){
34 canvas.onmousemove=function(e){
35 var e= event || ev;
36 var x = e.clientX-canvas.offsetLeft;
37 var y = e.clientY-canvas.offsetTop+document.body.scrollTop;
38
39 balls.push(new ball(x,y,Math.floor(Math.random()*30-5),Math.floor(Math.random()*6+1)));
40
41 }
42 };
43 canvas.onmouseup=function(){
44 canvas.onmousemove=null;
45 };
46
47 setInterval(function(){
48 cxt.clearRect(0,0,cxt.canvas.width,cxt.canvas.height);//清除画布20帧
49 for(var i = 0 ;i<balls.length;i++)
50 {
51 balls[i].x += balls[i].vx;
52 balls[i].y += balls[i].vy;
53 balls[i].vy += balls[i].g;
54 cxt.beginPath();
55 cxt.arc(balls[i].x,balls[i].y,balls[i].r,0,2*Math.PI);
56 cxt.closePath();
57 cxt.fillStyle=balls[i].color[balls[i].colorindex];
58 cxt.fill();
59 cxt.strokeStyle='white';
60 cxt.stroke();
61 document.title = balls.length;
62
63 if( balls[i].y>=500 - balls[i].r)
64 {
65 balls[i].y = 500 - balls[i].r;
66 balls[i].vy = - balls[i].vy*0.7;
67 }
68 if( balls[i].x>=1000 - balls[i].r )
69 {
70 balls[i].x = 1000 - balls[i].r ;
71 balls[i].vx = - balls[i].vx*0.7;
72 }
73 if(balls[i].x<=0+ balls[i].r)
74 {
75 balls[i].x = 0 + balls[i].r ;
76 balls[i].vx = - balls[i].vx*0.7;
77 }
78 };
79
80 },50);
81
82 clbtn.onclick=function(){
83 cxt.clearRect(0,0,cxt.canvas.width,cxt.canvas.height);
84 balls.splice(0,balls.length);//清空数组
85 };
86 }
87
88 </script>
89 </html>