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的一下基本用法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM