Canvas 同心圆旋转示例解析

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
    <canvas id='cvs' width='800' height='800' style='border:1px dotted blue'></canvas>

    <script>
        var cvs = document.getElementById('cvs');
        var ctx = cvs.getContext('2d');


        ctx.moveTo(0,400);
        ctx.lineTo(800,400);
        ctx.stroke();

        ctx.moveTo(400,0);
        ctx.lineTo(400,800);
        ctx.stroke();

        ctx.moveTo(400,400);
        // ctx.close();
        ctx.arc(400,400,20,0,2*Math.PI);
        ctx.stroke();

        ctx.arc(400,400,200,0,2*Math.PI);
        ctx.stroke();

        var deg = 0;// 角度 
        var rad = (deg/360)*2*Math.PI;// 角度 
        var R = 200; // 大圆半径
        var r = 20; // 小圆半径
        var a = 400; // 中心圆心
        var b = 400; // 中心圆心


        for(var i = 0; i < 360 / 30; i++)
        {
            deg = 0+30*i; // 30为小圆相对于大圆偏移的角度
            rad = (deg/360)*2*Math.PI;// 角度 
            y = a+Math.cos(rad)*R; // 当前时刻的小圆坐标y
            x = b+Math.sin(rad)*R; // 当前时刻的小圆坐标x
            ctx.moveTo(x,y); // 移动到小圆圆心
            ctx.beginPath(); // 开始记录路径
            ctx.arc(x,y,r,0,2*Math.PI); // 绘制小圆
            ctx.closePath(); // 结束记录路径 提笔
            ctx.stroke(); // 开始绘制保存路径
            
            ctx.beginPath(); // 开始记录路径
            ctx.moveTo(x,y); // 移动到当前小圆圆心
            ctx.lineTo(a,b); // 画线到中心圆心 辐射线
            ctx.closePath(); // 结束记录路径 提笔
            ctx.stroke(); // 开始绘制保存路径


            if(i == 1){    
                ctx.strokeStyle = 'red';
                
                ctx.beginPath(); // 开始记录路径
                ctx.moveTo(x,y); // 移动到当前小圆圆心
                ctx.lineTo(a,y); // 画垂线
                ctx.lineTo(a,b); // 画横坐标
                ctx.closePath(); // 结束记录路径 提笔
                ctx.stroke(); // 开始绘制保存路径

                ctx.beginPath(); // 开始记录路径
                ctx.moveTo(x,y); // 移动到当前小圆圆心
                ctx.lineTo(x,b); // 画垂线
                ctx.lineTo(a,b); // 画纵坐标
                ctx.closePath(); // 结束记录路径 提笔
                ctx.stroke(); // 开始绘制保存路径

                ctx.strokeStyle = 'green';
                ctx.beginPath();
                ctx.moveTo(a,b);
                ctx.arc(a,b,2*r,2*rad,3*rad);
                ctx.closePath();
                ctx.stroke();

                ctx.font = '30px Arial';
                ctx.fillText('A',a+5,b+r+50);

                ctx.font = '20px Arial';
                ctx.fillText('R*sin(A)',(x-90),y-10);

                ctx.font = '20px Arial';
                ctx.fillText('R*cos(A)',(x-10),y-50);


                ctx.strokeStyle = 'black';
            }
        }

    </script>


</body>
</html>

 

posted @ 2019-03-25 10:58  缘起花渊  阅读(623)  评论(0编辑  收藏  举报