1 <!doctype html> 2 <meta charset="UTF-8"> 3 <html> 4 <body> 5 <!--创建canvas标签--> 6 <!--canvas标签中的宽高不能设置在stlye里面否则不好定位x.y--> 7 <canvas id="canvas" width="500" height="500" style="background:#666"> 8 您的浏览器不支持canvas标签 9 </canvas> 10 <script> 11 var canvas=document.getElementById('canvas'); 12 //创建2d绘画环境 13 var cxt=canvas.getContext('2d'); 14 //声明一个时间参数(1:1天) 15 var time=0; 16 function draw(){ 17 //清除画布(清除之前的内容 重新画) 18 cxt.clearRect(0,0,500,500); 19 //画行星轨道 20 cxt.strokeStyle="#fff"; 21 cxt.beginPath(); 22 cxt.arc(250,250,120,0,360,false); 23 cxt.closePath(); 24 cxt.stroke(); 25 26 //画地球轨道 27 cxt.strokeStyle="#fff"; 28 cxt.beginPath(); 29 cxt.arc(250,250,100,0,360,false); 30 cxt.closePath(); 31 cxt.stroke(); 32 //画太阳 33 //重置0,0点 34 35 cxt.strokeStyle="red"; 36 cxt.lineWidth=1; 37 cxt.beginPath(); 38 cxt.arc(250,250,20,0,360,false); 39 cxt.closePath(); 40 //太阳需要填充颜色 41 //设置填充颜色(渐变色) 42 var grd=cxt.createRadialGradient(250,250,0,250,250,20); 43 grd.addColorStop(0,"#EEF920"); 44 grd.addColorStop(1,"RED"); 45 cxt.fillStyle=grd; 46 cxt.fill(); 47 //需要在异次元空间保存所有画布 48 cxt.save(); 49 //重置00点 50 cxt.translate(250,250); 51 //画地球 52 //设置选择弧度 53 //cxt.rotate(90*Math.PI/190); 54 //地球公转一周需要365天,time=1天 一天转365/360度 55 cxt.rotate(time*365/360*Math.PI/190); 56 cxt.beginPath(); 57 cxt.arc(0,-100,10,0,360,false); 58 cxt.closePath(); 59 //设置一下地球的颜色 60 var grd=cxt.createRadialGradient(0,-100,0,0,-100,10); 61 grd.addColorStop(0,"#78B1E8"); 62 grd.addColorStop(1,"#050C12"); 63 cxt.fillStyle=grd; 64 cxt.fill(); 65 66 //画行星 67 cxt.rotate((time*0.5)*365/360*Math.PI/190); 68 cxt.beginPath(); 69 cxt.arc(0,-120,10,0,360,false); 70 cxt.closePath(); 71 //设置一下行星的颜色 72 var xrd=cxt.createRadialGradient(0,-100,0,0,-100,10); 73 xrd.addColorStop(0,"#78B1E8"); 74 grd.addColorStop(1,"#050C12"); 75 cxt.fillStyle=xrd; 76 cxt.fillStyle=grd; 77 cxt.fill(); 78 cxt.restore(); 79 80 81 time +=1; 82 } 83 //使地球动起来 84 setInterval(draw,100); 85 </script> 86 87 </body> 88 </html>
效果图: