最近在写动画效果,需要获取圆上的点就简单的回顾了一下数学知识
这里圆点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