【canvas 太阳系的动画】

    xiaoxiao2022-07-07  155

    模拟 太阳系的动画 <!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();//创建图像对象1 = 太阳 var moon = new Image();//创建图像对象2 = 月球 var earth = new Image();//创建图像对象3 = 地球 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); //清空画布,要更新动画, 必须清空画布 clear canvas ctx.fillStyle = 'rgba(0,0,0,0.3)';//指定填充颜色 ctx.strokeStyle = 'rgba(0,153,255,0.4)';//指定绘线颜色 ctx.save();//保存状态 栈1 = 最初状态,原点在(0,0),没有移动过 // 画地球 Earth ctx.translate(150,150);//把画布原点 从(0,0) 移动到 (150,150) var time = new Date();//获取当前的日期和时间 ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );//从具体的日期和时间中提取出秒和毫秒字段,把顺时针旋转角度和 当前时间的 秒和毫秒变化 关联在一起 ctx.translate(105,0);//第二次移动原点,(150,150)水平向右移动105,把地球放在 绘线上 ctx.fillRect(0,-12,50,24); // 画1个矩形,作为地球图形上的另一半遮盖住,当作阴影 Shadow ctx.drawImage(earth,-12,-12);//把地球图形,添加到画布上 //画月球 Moon ctx.save();//保存当前的状态 栈2 ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() );//月球旋转角度,和当前时间变换关联在一起 ctx.translate(0,28.5);//第三次 移动原点,(150+105,150)下移 28.5 (150+105,150+28.5) ctx.drawImage(moon,-3.5,-3.5);//画月球 //画地球旋转轨道 ctx.restore();//恢复状态,当前状态=栈2 ctx.restore();//恢复状态,当前状态=栈1=最初状态 (原点没有移动过) ctx.beginPath(); ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit,关联关系,半径 = 地球相对第二原点(150,150) 向右移动的距离 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
    最新回复(0)