js实现圆周
JavaScript 实现圆周运动
在 JavaScript 中实现圆周运动通常涉及三角函数(Math.sin 和 Math.cos)来计算圆周上的点坐标。以下是几种常见的实现方式:
使用 Canvas 绘制圆周运动
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let angle = 0;
const radius = 50;
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 计算圆周上的点坐标
const x = centerX + Math.cos(angle) * radius;
const y = centerY + Math.sin(angle) * radius;
// 绘制圆和运动点
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
ctx.stroke();
ctx.beginPath();
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fill();
angle += 0.05;
requestAnimationFrame(animate);
}
animate();
使用 CSS 和 JavaScript 实现圆周运动
通过动态更新 CSS 的 transform 属性实现圆周运动:
const element = document.getElementById('circle');
let angle = 0;
const radius = 100;
function animate() {
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius;
element.style.transform = `translate(${x}px, ${y}px)`;
angle += 0.05;
requestAnimationFrame(animate);
}
animate();
参数说明
angle:当前角度(弧度制),随时间递增。radius:圆周运动的半径。centerX和centerY:圆心坐标(Canvas 示例中为画布中心)。
扩展:椭圆运动
通过调整 x 和 y 方向的半径,可以实现椭圆运动:
const x = centerX + Math.cos(angle) * radiusX;
const y = centerY + Math.sin(angle) * radiusY;
性能优化
- 使用
requestAnimationFrame实现平滑动画。 - 避免频繁的 DOM 操作(如 CSS 示例中可缓存
transform值)。







