在 JavaScript 中,可以通过 requestAnimationFrame
和数学公式来实现圆周运动效果。以下是示例代码:
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript 圆周运动</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: #f4f4f4;
}
.orbit {
position: relative;
width: 200px;
height: 200px;
border: 1px dashed #aaa; /* 圆形轨道 */
border-radius: 50%; /* 圆形 */
}
.object {
position: absolute;
width: 20px;
height: 20px;
background: red;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="orbit">
<div class="object"></div>
</div>
<script>
// 获取元素
const object = document.querySelector('.object');
const orbit = document.querySelector('.orbit');
// 圆心和半径
const centerX = orbit.offsetWidth / 2;
const centerY = orbit.offsetHeight / 2;
const radius = centerX - 10; // 轨道半径,减去 object 的一半宽度
let angle = 0; // 当前角度
// 动画函数
function animate() {
// 计算物体的 x 和 y 坐标
const x = centerX + radius * Math.cos(angle) - object.offsetWidth / 2;
const y = centerY + radius * Math.sin(angle) - object.offsetHeight / 2;
// 设置物体位置
object.style.transform = `translate(${x}px, ${y}px)`;
// 增加角度
angle += 0.02; // 控制速度,值越大速度越快
// 循环动画
requestAnimationFrame(animate);
}
// 开始动画
animate();
</script>
</body>
</html>
代码解析
-
轨道和圆心:
- 获取轨道的宽度和高度,并通过
offsetWidth
和offsetHeight
计算圆心的坐标(centerX, centerY)
。 - 定义半径
radius
,根据轨道大小减去运动物体的一半宽度。
- 获取轨道的宽度和高度,并通过
-
角度计算:
- 使用角度变量
angle
表示当前的旋转位置,单位为弧度。 - 每帧增加一个小的角度值(如
0.02
)来控制匀速运动。
- 使用角度变量
-
坐标计算公式:
- 水平方向 ( x = \text{centerX} + \text{radius} \cdot \cos(\text{angle}) )
- 垂直方向 ( y = \text{centerY} + \text{radius} \cdot \sin(\text{angle}) )
-
元素位置更新:
- 使用
transform: translate(x, y)
设置物体的新位置。
- 使用
-
动画循环:
- 使用
requestAnimationFrame
来创建平滑的动画循环。
- 使用
参数调整
- 速度: 修改
angle += 0.02
,值越大,运动越快。 - 轨道大小: 改变
.orbit
的宽高,同时调整radius
值。 - 初始位置: 调整
angle
的初始值(例如Math.PI / 2
表示从顶部开始)。