js获取圆上的点

最近在写动画效果,需要获取圆上的点就简单的回顾了一下数学知识

ä»»æè§ä¸è§å½æ°                                  ç´è§ä¸è§å½¢

这里圆点0 为圆心,我们需要知道A点的(x,y)坐标,因为这个点就是在圆点上,而r就是半径,通过三角函数可得出:

cos(A) = c/b;             sin(A) = c/a;         

转换到坐标系中就是:

sin(o) = r / y;     cos(o) = r / x;         x= cos(o)*r;                 y=sin(o)*r;

转换成js的函数表达式就是:

let x = ce.x +  Math.cos(Math.PI * 2 / 360 * degree) * r;
let y = ce.y+ Math.sin(Math.PI * 2 / 360 * degree) * r;

其中ce为圆心点     degree为度数(0-360);r为圆半径;

写个例子测试一下(用canvas绘制一个圆并在圆上面绘制小圆):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<canvas id="circle" width="800" height="500"></canvas>

<script>

    //    获取圆上的点
    let center = {
        x: 250,
        y: 250
    };
    let radius = 150;
    let cxt = null;

    function initCanvas() {
        cxt = document.getElementById('circle').getContext('2d');
        cxt.fillStyle = '#000';
        cxt.fillRect(0, 0, 800, 500);
    }

    function getCirclePoint(center, radius) {
        let ce = center;
        let r = radius;
        let c = radius;
        let points = [];
        let degree = 30;
        cxt.arc(ce.x,ce.y,r,0,360);
        cxt.strokeStyle = '#fff';
        cxt.stroke();
        cxt.save();
        for (let i = 0; i < 12; i++) {
            degree = i*30;
            //通过数学函数获取点
            console.log('Math.PI * 2 / 360 * degree',Math.PI * 2 / 360 * degree);
            let x = ce.x +  Math.cos(Math.PI * 2 / 360 * degree) * r;
            let y = ce.y+ Math.sin(Math.PI * 2 / 360 * degree) * r;
            points.push({
                x:x,
                y:y
            });
            cxt.beginPath();
            cxt.arc(x,y,5,0,360);
            cxt.strokeStyle = '#fff';
            cxt.stroke();
            cxt.closePath();
            cxt.save();
        }
    }

    initCanvas();
    getCirclePoint(center, radius);
</script>
</body>
</html>

更多js的数学函数查看菜鸟教程:http://www.runoob.com/jsref/jsref-obj-math.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值