js实现圆圈运动
使用 Canvas 实现圆圈运动
在 HTML 中创建 Canvas 元素并初始化绘图环境:
<canvas id="circleCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('circleCanvas');
const ctx = canvas.getContext('2d');
</script>
定义圆心坐标和半径:
let centerX = canvas.width / 2;
let centerY = canvas.height / 2;
let radius = 50;
使用 requestAnimationFrame 实现动画循环:

let angle = 0;
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.strokeStyle = '#ddd';
ctx.stroke();
// 绘制运动点
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
angle += 0.05;
requestAnimationFrame(animate);
}
animate();
使用 CSS 动画实现圆圈运动
创建 HTML 元素结构:
<div class="circle-container">
<div class="circle"></div>
</div>
添加 CSS 样式和动画:

.circle-container {
width: 200px;
height: 200px;
position: relative;
border: 1px dashed #ccc;
border-radius: 50%;
}
.circle {
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
position: absolute;
top: -10px;
left: 90px;
animation: circle-motion 3s linear infinite;
}
@keyframes circle-motion {
0% {
transform: rotate(0deg) translateY(-100px) rotate(0deg);
}
100% {
transform: rotate(360deg) translateY(-100px) rotate(-360deg);
}
}
使用 SVG 实现圆圈运动
创建 SVG 元素和动画:
<svg width="200" height="200" viewBox="0 0 200 200">
<circle cx="100" cy="100" r="80" stroke="#ddd" fill="none"/>
<circle cx="180" cy="100" r="10" fill="red">
<animateTransform
attributeName="transform"
type="rotate"
from="0 100 100"
to="360 100 100"
dur="3s"
repeatCount="indefinite"/>
</circle>
</svg>
使用三角函数计算位置
通过 JavaScript 定时更新元素位置:
const dot = document.getElementById('movingDot');
let angle = 0;
const radius = 80;
const center = { x: 100, y: 100 };
setInterval(() => {
angle += 0.05;
const x = center.x + Math.cos(angle) * radius;
const y = center.y + Math.sin(angle) * radius;
dot.style.left = `${x}px`;
dot.style.top = `${y}px`;
}, 16);
以上方法分别展示了使用不同技术实现圆圈运动的效果,可根据具体需求选择合适的方式。Canvas 适合需要复杂绘制的场景,CSS 动画实现简单但控制精度较低,SVG 适合矢量图形,纯 JavaScript 计算则提供最大灵活性。






