欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

canvas初学 半动态画太极图

程序员文章站 2022-06-27 08:00:47
可直接复制粘贴运行

可直接复制粘贴运行

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>canvas</title>
</head>
<body>
    <canvas width="1000" height="1000" id="mycvs">当前浏览器不支持此控件,请更换或更新浏览器</canvas>
    <script type="text/javascript">
        var a = document.getElementById("mycvs");
        var can = a.getContext("2d");
        var beginx = -(1 / 2 * Math.PI);//起始值
        var r = 150;
        var sidex = 1 * (Math.PI / 180);//增加值
        var endx = beginx + 2 * Math.PI;//结束值
        var bendx = beginx + 2 * Math.PI;
        var aendx = beginx + Math.PI;
        var tmx = beginx;//当前值
        var t = 0;
        var rends = function () {
            if (tmx + sidex >= endx) {
                tmx = beginx;
                t = t + 1;
                endx = endx - Math.PI;
                if (t == 2) {//填充颜色并退出
                    can.save();    
                    arcs(300, 300, r, beginx, aendx, true, "black");
                    arcs(300, 225, 75, beginx, aendx,null,"black");
                    arcs(300, 375, 75, beginx, aendx, true,"white");
                    arcs(300, 375, 20, beginx, bendx, null, "black");
                    arcs(300, 225, 20, beginx, bendx, null, "white");
                    return;
                }
            } else {
                tmx += sidex;
            }
            can.clearRect(0, 0, 1000, 1000);//用clearRect()函数使图像更加清晰 也造成一笔结束后上一笔清除了
            can.lineWidth = 5;
            if (t == 0)
            {           
            can.beginPath();
            can.arc(300, 300, r, beginx, tmx);           
            can.stroke();
            } else if (t == 1) {               
                can.beginPath();
                can.arc(300, 300, r, beginx, bendx);//所以在这里我又重新画了一遍外圆
        
                can.arc(300, 225, 75, beginx, tmx);
                can.arc(300, 375, 75, beginx, tmx, true);                         
                can.stroke();             
            }
            requestAnimationFrame(rends);//这个是动画控制
               
        };


        function arcs(x,y,r,begin,end,f,color) {//圆心(x,y),半径r,起始值begin,结束值end,方向f,填充颜色color
            can.beginPath();
            can.fillStyle = color;
            can.arc(x, y, r, begin, end,f);
            can.fill();
            can.stroke();
        }
        rends();

   </script>
</body>
</html>

这个代码有点冗余,初学者请多多指教谢谢。