Canvas帧数和步长实例

 1 <!DOCTYPE HTML>
 2 <html lang="zh-CN">
 3     <head>
 4         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5         <title>test</title>
 6     </head>
 7 
 8 <body>
 9 
10 <Canvas id="canvas1" width="230" height="600" style="background-color:black"> 
11 你的浏览器不支持 Canvas 标签,请使用 Chrome 浏览器 或者 FireFox 浏览器 
12 </canvas><br/> 
13 帧数:<input id="txt1" type="text" value="25"/><br/> 
14 每次移动距离:<input type="text" id="txt2" value="10"/>px<br/> 
15 <input type="button" value="开始"  onclick="move_box()" /> 
16 <input type="button" value="暂停" onclick="stop()" /> 
17 <script type="text/javascript"> 
18 //定时器 
19 var interval=null; 
20 //停止动画 
21 function stop(){ 
22     clearInterval(interval); 
23 } 
24 //====================
25 //基本动画 
26 //===================
27 function move_box(){ 
28     //停止动画 
29     stop(); 
30     //移动速度 
31     var delta=parseInt(document.getElementById('txt2').value); 
32     //每秒绘制多少次 
33     var fps=parseInt(document.getElementById('txt1').value); 
34     //画布对象 
35     var canvas=document.getElementById("canvas1") 
36     //获取上下文对象 
37     var ctx = canvas.getContext("2d"); 
38     //设置颜色 
39     ctx.fillStyle="red"; 
40     //方块的初始位置 
41     var x=100;var y=30; 
42     //方块的长度和宽度 
43     var w=30;var h=30; 
44     //开始动画 
45     interval = setInterval(function(){ 
46         //改变 y 坐标 
47         y=y+delta; 
48         //上边缘检测 
49         if(y<0){ 
50         y=0; 
51         delta=-delta; 
52         } 
53         
54         //下边缘检测 
55         if((y+h)>canvas.getAttribute("height")){ 
56         y=canvas.getAttribute("height")-h; 
57         delta=-delta; 
58         } 
59         //清空画布 
60         ctx.clearRect(0,0,canvas.getAttribute("width"),canvas.getAttribute("height")); 
61         //保存状态 
62         ctx.save(); 
63         //移动坐标 
64         ctx.translate(x,y); 
65         //重新绘制 
66         ctx.fillRect(0,0,w,h); 
67         //恢复状态 
68         ctx.restore(); 
69         },1000/fps); 
70 } 
71 </script>
72 
73 
74 </body>
75 </html>
原文地址:https://www.cnblogs.com/linn/p/3387835.html