开源canvas比较高级的旋转的太极图的源码

一些代码部分我打了注释,清晰明了,有不懂得直接评论即可,然后就是废话不多说上代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>用canvas制作会旋转的太极图的源码</title>
    <style type="text/css">
      #myCanvas{
        /* 给太极图一个背景方便看白色轮廓 */
        background: #ccc;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="400">
      <script type="text/javascript">
        function runTaiji(s) {
          // 可以根据自己的想要的速度传参,s越大速度越快
          let v = s/36000;  
          let i = 1;
          function fillTaiji() {
            var c = document.getElementById("myCanvas");
            var ctx = c.getContext("2d");
            ctx.clearRect(0,0,600,400);
            // 此处保存原始坐标
            ctx.save();
            ctx.translate(300,200);
            // var time = new Date();
            // ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() )
            ctx.rotate(((2*Math.PI)*v)*i++);
            if (i === 36000) {
              i = 1;
            }
            //绘制左侧的白色半圆直径都是150
            ctx.fillStyle = "#FFFFFF";
            ctx.beginPath();
            ctx.arc(0, 0, 150, 1.5 * Math.PI, Math.PI / 2, false);
            ctx.closePath();
            ctx.fill();
            //绘制右侧的黑色半圆
            ctx.fillStyle = "#000000";
            ctx.beginPath();
            ctx.arc(0, 0, 150, Math.PI / 2, 1.5 * Math.PI, false);
            ctx.closePath();
            ctx.fill();
            //绘制下面的黑色圆
            ctx.fillStyle = "#000000";
            ctx.beginPath();
            ctx.arc(0, 75, 75, 0, 2 * Math.PI, false);
            ctx.closePath();
            ctx.fill();
            //绘制上面的白色圆
            ctx.fillStyle = "#FFFFFF";
            ctx.beginPath();
            ctx.arc(0, -75, 75, 0, 2 * Math.PI, false);
            ctx.closePath();
            ctx.fill();
            //绘制两个小圆
            ctx.fillStyle = "FFFFFF";
            ctx.beginPath();
            ctx.arc(0, 75, 10, 0, 2 * Math.PI, false);
            ctx.closePath();
            ctx.fill();
            //绘制黑色小圆
            ctx.fillStyle = "#000";
            ctx.beginPath();
            ctx.arc(0, -75, 10, 0, 2 * Math.PI, false);
            ctx.closePath();
            ctx.fill();
            
            ctx.closePath();
            ctx.restore();
            // 此处恢复原始坐标
            window.requestAnimationFrame(fillTaiji)
            // window.requestAnimationFrame() 
            // 告诉浏览器——你希望执行一个动画,
            // 并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。
            // 该方法需要传入一个回调函数作为参数,
            // 该回调函数会在浏览器下一次重绘之前执行
          }
          window.requestAnimationFrame(fillTaiji)
        }
        runTaiji(100);
      </script>
  </body>
</html>

实际效果不卡顿,录屏软件有点渣渣 

猜你喜欢

转载自blog.csdn.net/weixin_41229588/article/details/107922449