学习目的:通过JavaScript操控<canvas>对象,实现交互动画。
动画的基本步骤
1. 清空canvas,使用clearRect方法
2. 保存canvas状态
3. 绘制动画图形
4. 恢复canvas状态
操控动画Controlling an animation
setInterval(function, delay)
setTimeout(function, delay)
requestAnimationFrame(callback)
太阳系运动的小例子
<canvas id="canvas" width="300" height="300"></canvas>
<script type="text/javascript"> var sun = new Image(); var moon = new Image(); var earth = new Image(); var cvs = document.getElementById("canvas"); /** * 创建三张图片并完成动画 * @return {[type]} [description] */ function init(){ sun.src = "image/Canvas_sun.png"; earth.src = "image/Canvas_earth.png"; moon.src = "image/Canvas_moon.png"; requestAnimationFrame(draw); } /** * 分别通过平移旋转来设置不同的canvas状态完成三张图片的绘制 * @return {[type]} [description] */ function draw(){ if(cvs.getContext){ var ctx = cvs.getContext("2d"); ctx.globalCompositeOperation = "destination-over"; //1. 清空clearRect ctx.clearRect(0,0,300,300); //2. 保存canvas状态 ctx.fillStyle = "rgba(0,0,0,0,4)"; ctx.strokeStyle = "rgba(0,153,255,0.4)"; ctx.save(); ctx.translate(150,150);//sun图片大小为300*300 //3. 绘制图片 var time = new Date(); //绘制地球 ctx.rotate((2*Math.PI/60)*time.getSeconds()+(2*Math.PI/60000)*time.getMilliseconds());//1分钟=60秒,设置地球围绕太阳的旋转周期为1min ctx.translate(105, 0);//地球运行轨迹半径为105 ctx.fillRect(0,-12,50,24);//地球阴影 ctx.drawImage(earth, -12, -12);//地球图片大小为24*24 ctx.beginPath(); ctx.arc(0,0,28.5,0,Math.PI*2,false); ctx.closePath(); ctx.stroke();ctx.save();
//绘制月球//此时canvas状态为默认状态 ctx.rotate((2*Math.PI/60)*time.getSeconds()+(2*Math.PI/60000)*time.getMilliseconds()); ctx.translate(0,28.5);//月球的运行轨迹半径为28.5 ctx.drawImage(moon, -3.5, -3.5);//月球图片大小为7*7ctx.restore();
ctx.restore(); //最初的canvas状态 ctx.beginPath(); ctx.arc(150,150,105,0,Math.PI*2,false); ctx.closePath(); ctx.stroke(); ctx.drawImage(sun, 0, 0, 300, 300);requestAnimationFrame(draw);
} } init(); </script>
canvas绘制动画时钟
绘制时钟的方法有很多,分别介绍下不同的思路:
1. 利用canvas来绘制动画时钟,通过平移旋转来实现线段和圆的绘制
2. 利用HTML+CSS3来绘制动画时钟,也是通过CSS3的变形属性来实现线段和圆的绘制
这两种实现方法都需要通过JavaScript来确定当前的时间点,从而确定各个指针的初始位置。
绘制小球
加入控制元素,如物理碰撞检测等