模拟 太阳系的动画
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="300" height="300" style="border:1px solid">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var sun = new Image();
var moon = new Image();
var earth = new Image();
function init(){
sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
window.requestAnimationFrame(draw);
}
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
ctx.clearRect(0,0,300,300);
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.strokeStyle = 'rgba(0,153,255,0.4)';
ctx.save();
ctx.translate(150,150);
var time = new Date();
ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );
ctx.translate(105,0);
ctx.fillRect(0,-12,50,24);
ctx.drawImage(earth,-12,-12);
ctx.save();
ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() );
ctx.translate(0,28.5);
ctx.drawImage(moon,-3.5,-3.5);
ctx.restore();
ctx.restore();
ctx.beginPath();
ctx.arc(150,150,105,0,Math.PI*2,false);
ctx.stroke();
ctx.drawImage(sun,0,0,300,300);
window.requestAnimationFrame(draw);
}
init();
</script>
</body>
</html>
形成的动图图形相对关系原点移动分析
知识拓展:获取当前日期和时间: new Date()
Date 对象用于: 处理日期和时间。定义 Date 对象: 通过 new 关键词
以下代码定义了名为 myDate 的 Date 对象:var myDate=new Date() ; 注释:Date 对象 自动使用 当前的日期和时间 作为其初始值。获取秒: getSeconds() 方法
返回秒: getSeconds() 方法可返回 时间的秒。语法:dateObject.getSeconds()返回值: 一个整数 ( 0 ~ 59 之间)
dateObject 的分钟字段,以本地时间显示。 获取毫秒: getMilliseconds() 方法
1秒(s)=1000毫秒(ms)getMilliseconds() 方法可返回 时间的毫秒。语法: dateObject.getMilliseconds()返回值: 一个整数 (0 ~ 999 之间)dateObject 的毫秒字段,以本地时间显示。
原图链接 保存:太阳: 地球:
月球:
参考文档: MDN Canvas教程
感谢:♥♥♥ 如果这篇文章对您有帮助的话,可以点赞、评论、关注,鼓励下作者哦,感谢阅读 O(∩_∩)O哈哈~
转载 请注明出处 ,Thanks♪(・ω・)ノ
作者:Hey_Coder来源:原文:https://blog.csdn.net/VickyTsai/article/details/90453691