Fork me on GitHub

Canvas实现曲线运动

  • 前言

    Html5添加的最受欢迎的功能就是<canvas>元素,它负责在页面中设定一个区域,然后在里面可以通过javascript动态地在其内绘制图形。

    主流浏览器,IE9+,手机端都是支持它的。

  • 创建Canvas

    要使用Canvas元素就必须先设置其width和height,指定绘图区域的大小

    类似:<canvas id="canvas" width="800" height="800"/> 

    如果要在这块画布上绘图的话,首先要取得绘图上下文,需调用getContext()方法

       var canvas=document.getElementById("canvas");

        //判断浏览器是否支持canvas

      if(canvas.getContext)

      {   var draw=canvas.getContext("2d");//这里2d  取得2d上线文对象,还有一个WebGL的3D上下文(还未接触过,不在此陈诉了)

      }

    我们用2d上下文可以绘制简单的2d图形,如矩形,弧线。

  • 利用Canvas创建曲线运动

这里有个demo是曲线运动,直接上代码

 1 <!DOCTYPE html>
 2 <html> 
 3 <head> 
 4 <meta charset=gbf> 
 5 <title>曲线运动</title> 
 6 <script> 
 7 //box 
 8 var box_x=0; 
 9 var box_y=0; 
10 var box_width=500; 
11 var box_height=500; 
12 //ball 
13 var ball_x=10; 
14 var ball_y=10; 
15 var ball_radius=10; 
16 var ball_vx=10; 
17 var ball_vy=0; 
18 //constant 
19 var g=10;//note 
20 var rate=0.9; 
21 //bound 
22 var bound_left=box_x+ball_radius; 
23 var bound_right=box_x+box_width-ball_radius; 
24 var bound_top=box_y+ball_radius; 
25 var bound_bottom=box_y+box_height-ball_radius; 
26 //context 
27 var ctx; 
28 function init() 
29 { 
30 ctx=document.getElementById('canvas').getContext('2d'); 
31 //
32 ctx.lineWidth=ball_radius; 
33 //设置球的颜色
34 ctx.fillStyle="rgb(200,0,50)"; 
35 move_ball(); 
36 setInterval(move_ball,100); 
37 } 
38 
39 function move_ball() 
40 { 
41 //清除画布上的矩形区域
42 ctx.clearRect(box_x,box_y,box_width,box_height); 
43 move_and_check(); 
44 //开始曲线路径
45 ctx.beginPath(); 
46 //绘制圆球
47 ctx.arc(ball_x,ball_y,ball_radius,0,Math.PI*2,true); 
48 //fillstyle填充
49 ctx.fill(); 
50 //绘制指定矩形
51 ctx.strokeRect(box_x,box_y,box_width,box_height); 
52 } 
53 
54 function move_and_check() 
55 { 
56 var cur_ball_x=ball_x+ball_vx; 
57 var temp=ball_vy; 
58 ball_vy=ball_vy+g; 
59 var cur_ball_y=ball_y+ball_vy+g/2; 
60 if(cur_ball_x<bound_left) 
61 { 
62 cur_ball_x=bound_left; 
63 ball_vx=-ball_vx*0.9; 
64 ball_vy=ball_vy*0.9; 
65 } 
66 if(cur_ball_x>bound_right) 
67 { 
68 cur_ball_x=bound_right; 
69 ball_vx=-ball_vx*0.9; 
70 ball_vy=ball_vy*0.9; 
71 } 
72 if(cur_ball_y<bound_top) 
73 { 
74 cur_ball_y=bound_top; 
75 ball_vy=-ball_vy*0.9; 
76 ball_vx=ball_vx*0.9; 
77 } 
78 if(cur_ball_y>bound_bottom) 
79 { 
80 cur_ball_y=bound_bottom; 
81 ball_vy=-ball_vy*0.9; 
82 ball_vx=ball_vx*0.9; 
83 } 
84 ball_x=cur_ball_x; 
85 ball_y=cur_ball_y; 
86 } 
87 </script> 
88 </head> 
89 <body onLoad="init()"> 
90 <canvas id="canvas" width="800" height="800"/> 
91 </body> 
92 </html>
View Code

代码中包含了少部分2D上下文API。详细API请参考:

http://www.w3school.com.cn/html5/html_5_canvas.asp;

http://blog.teamtreehouse.com/getting-started-with-the-canvas-api

http://javascript.ruanyifeng.com/htmlapi/canvas.html

  • 最后

      很多css3不能表现的复杂动画,通过canvas,js来配合解决是极好的,当然这里面还有很多东西,这里小小记录下canvas的一下基本用法。

posted @ 2015-03-26 22:43  Kingler  阅读(3660)  评论(0编辑  收藏  举报