JavaScript实现圆周运动效果

在 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>

在这里插入图片描述

代码解析

  1. 轨道和圆心:

    • 获取轨道的宽度和高度,并通过 offsetWidthoffsetHeight 计算圆心的坐标 (centerX, centerY)
    • 定义半径 radius,根据轨道大小减去运动物体的一半宽度。
  2. 角度计算:

    • 使用角度变量 angle 表示当前的旋转位置,单位为弧度。
    • 每帧增加一个小的角度值(如 0.02)来控制匀速运动。
  3. 坐标计算公式:

    • 水平方向 ( x = \text{centerX} + \text{radius} \cdot \cos(\text{angle}) )
    • 垂直方向 ( y = \text{centerY} + \text{radius} \cdot \sin(\text{angle}) )
  4. 元素位置更新:

    • 使用 transform: translate(x, y) 设置物体的新位置。
  5. 动画循环:

    • 使用 requestAnimationFrame 来创建平滑的动画循环。

参数调整

  • 速度: 修改 angle += 0.02,值越大,运动越快。
  • 轨道大小: 改变 .orbit 的宽高,同时调整 radius 值。
  • 初始位置: 调整 angle 的初始值(例如 Math.PI / 2 表示从顶部开始)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值