标签:style blog http io ar color os sp java
canvas可以绘制图像,自然而然的就可以制作动画,因为动画的每一帧都是图像。我们可以利用javascript的setInterval函数来实现动画效果。
下面是一个例子,小圆绕着红点圆心不停的转圆圈。
代码:
1 <canvas id="myCanvas" width="300" height="300"> 2 您的浏览器不支持canvas! 3 </canvas> 4 <script> 5 var canvas = document.getElementById(‘myCanvas‘); 6 if (canvas.getContext) { 7 var context = canvas.getContext(‘2d‘); 8 var posX = 100, 9 posY = 150, 10 flag = true; 11 12 setInterval(function() { 13 14 context.fillStyle = "#ccc"; 15 context.fillRect(0,0,canvas.width, canvas.height); 16 context.beginPath(); 17 context.fillStyle = "white"; 18 19 context.arc(posX, posY, 20, 0, Math.PI*2, true); 20 context.closePath(); 21 context.fill(); 22 23 console.log(posX + "," + posY); 24 if(flag && posX < 201) { 25 posX += 1; 26 } else { 27 posX -= 1; 28 flag = false; 29 if(posX < 100) { 30 flag = true; 31 } 32 } 33 if(flag) { 34 posY = 150-Math.sqrt(2500-Math.pow(posX-150, 2)); 35 } else { 36 posY = 150+Math.sqrt(2500-Math.pow(posX-150, 2)); 37 } 38 39 context.beginPath(); 40 context.arc(150, 150, 2, 0, Math.PI*2, true) 41 context.fillStyle = "red"; 42 context.fill(); 43 44 }, 50); 45 } 46 </script>
标签:style blog http io ar color os sp java
原文地址:http://www.cnblogs.com/xiyangbaixue/p/4106188.html