首先声明一点:自己学习的程序来源于:
/zh-CN/docs/Web/API/Canvas_API/Tutorial/Basic_animations
代码学习来源
下面直接放自己的代码:html代码:
<!DOCTYPE html><html><head><meta charset="utf-8"><title>基本动画-太阳地球月亮</title></head><body><canvas id="canvas" width="300" height="300"></canvas></body><script src="animation_sunearthmoon_copy_self.js"></script></html>
下面再放js代码
//创建太阳,月亮,地球,背景;function draw(){var ctx=document.getElementById('canvas').getContext('2d');//ctx.globalCompositeOperation = 'destination-over';//设置背景ctx.fillStyle='black';ctx.fillRect(0,0,300,300);ctx.save();ctx.translate(150,150);//下一步画地球;var time= new Date();ctx.rotate(((2*Math.PI)/60)*time.getSeconds()+((2*Math.PI)/60000)*time.getMilliseconds());//这个rotate就相当于是前一个坐标进行旋转(ctx.translate(150,150));ctx.translate(110,0);//移动坐标后画一个地球;ctx.fillStyle='green';ctx.beginPath();ctx.arc(0,0,15,0,2*Math.PI,true);//设定地球大小为20;ctx.fill();//moonctx.save();ctx.rotate(((2*Math.PI)/6)*time.getSeconds()+((2*Math.PI)/6000)*time.getMilliseconds());ctx.translate(40,0);ctx.fillStyle='red';ctx.beginPath();ctx.arc(0,0,8,0,2*Math.PI,true);ctx.fill();//ctx.save();ctx.restore();//起到的作用是把坐标系回归一次;//下一步就是画太阳;ctx.restore();ctx.beginPath();ctx.fillStyle='blue';ctx.arc(150,150,110,0,2*Math.PI,true);ctx.stroke();ctx.fillStyle='orange';ctx.beginPath();ctx.arc(150,150,30,0,2*Math.PI,true);//设定太阳大小为30;ctx.fill();//到此太阳完成;window.requestAnimationFrame(draw);}draw();