返回

圆周运动?不止一种方法!

前端

CSS方法

CSS中的motion-path属性可以让你指定一个元素在一定时间内应该沿着什么路径移动。以下是如何用motion-path实现圆周运动:

  1. 首先,创建一个HTML元素,比如一个div。
  2. 然后,使用motion-path属性指定元素的运动路径。路径可以是任意形状,但对于圆周运动,我们将使用一个圆形。
  3. 最后,使用animation属性指定动画的持续时间和循环次数。
div {
  width: 50px;
  height: 50px;
  background-color: red;
  animation: move 2s infinite;
}

@keyframes move {
  from {
    motion-path: path("M 0 0 a 50 50 0 1 1 100 0");
  }
  to {
    motion-path: path("M 0 0 a 50 50 0 1 0 100 0");
  }
}

JavaScript方法

JavaScript也可以用来让小球做圆周运动。以下是如何使用JavaScript实现圆周运动:

  1. 首先,创建一个canvas元素。
  2. 然后,使用JavaScript创建一个context对象。
  3. 使用context对象的arc()方法绘制一个圆。
  4. 最后,使用requestAnimationFrame()方法不断更新圆的位置,使其看起来像在做圆周运动。
<canvas id="canvas" width="500" height="500"></canvas>

<script>
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

  // 绘制一个圆
  ctx.beginPath();
  ctx.arc(250, 250, 50, 0, 2 * Math.PI);
  ctx.stroke();

  // 不断更新圆的位置
  function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 计算圆的新位置
    var angle = Date.now() / 1000;
    var x = 250 + 50 * Math.cos(angle);
    var y = 250 + 50 * Math.sin(angle);

    // 绘制圆
    ctx.beginPath();
    ctx.arc(x, y, 50, 0, 2 * Math.PI);
    ctx.stroke();

    // 请求下一次更新
    requestAnimationFrame(update);
  }

  update();
</script>

Canvas方法

Canvas也可以用来让小球做圆周运动。以下是如何使用Canvas实现圆周运动:

  1. 首先,创建一个canvas元素。
  2. 然后,使用JavaScript创建一个context对象。
  3. 使用context对象的arc()方法绘制一个圆。
  4. 最后,使用requestAnimationFrame()方法不断更新圆的位置,使其看起来像在做圆周运动。
<canvas id="canvas" width="500" height="500"></canvas>

<script>
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

  // 绘制一个圆
  ctx.beginPath();
  ctx.arc(250, 250, 50, 0, 2 * Math.PI);
  ctx.stroke();

  // 不断更新圆的位置
  function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 计算圆的新位置
    var angle = Date.now() / 1000;
    var x = 250 + 50 * Math.cos(angle);
    var y = 250 + 50 * Math.sin(angle);

    // 绘制圆
    ctx.beginPath();
    ctx.arc(x, y, 50, 0, 2 * Math.PI);
    ctx.stroke();

    // 请求下一次更新
    requestAnimationFrame(update);
  }

  update();
</script>