js实现圆圈运动
实现圆圈运动的 JavaScript 方法
使用 Canvas 绘制圆圈运动
通过 HTML5 Canvas 和 JavaScript 可以实现平滑的圆圈运动。以下是具体实现代码:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let angle = 0;
const radius = 50;
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
function drawCircleMotion() {
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(x, y, 10, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
angle += 0.05;
requestAnimationFrame(drawCircleMotion);
}
drawCircleMotion();
HTML 部分需要添加 Canvas 元素:
<canvas id="myCanvas" width="400" height="400"></canvas>
使用 CSS 和 JavaScript 实现圆圈运动
可以通过 CSS 动画结合 JavaScript 计算位置来实现:
const element = document.getElementById('movingObject');
let angle = 0;
const radius = 100;
function updatePosition() {
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius;
element.style.transform = `translate(${x}px, ${y}px)`;
angle += 0.05;
requestAnimationFrame(updatePosition);
}
updatePosition();
对应的 HTML 和 CSS:
<div id="movingObject" style="width:20px; height:20px; background:red; border-radius:50%; position:absolute;"></div>
使用 SVG 实现圆圈运动
通过 SVG 和 JavaScript 也可以实现类似的运动效果:
const svg = document.getElementById('mySvg');
const circle = document.getElementById('movingCircle');
let angle = 0;
const radius = 50;
const centerX = 100;
const centerY = 100;
function animate() {
const x = centerX + Math.cos(angle) * radius;
const y = centerY + Math.sin(angle) * radius;
circle.setAttribute('cx', x);
circle.setAttribute('cy', y);
angle += 0.05;
requestAnimationFrame(animate);
}
animate();
对应的 SVG 代码:

<svg id="mySvg" width="200" height="200">
<circle id="movingCircle" r="10" fill="green"/>
</svg>
参数说明
angle:当前角度,以弧度表示radius:运动轨迹的半径centerX/Y:圆心的坐标位置requestAnimationFrame:浏览器提供的动画API,比setInterval更流畅
这些方法都可以实现平滑的圆圈运动效果,选择哪种方法取决于具体应用场景和性能需求。Canvas 适合复杂的图形处理,CSS 方法适合简单的 UI 元素动画,SVG 则适合矢量图形的动画效果。





