如何在动画期间更改 y 位置

How to change y position during animation

我正在 canvas 内绘制动画圆圈,到目前为止我设法让它在 canvas 内从左到右移动。 我需要做的是,当圆到达它最右边的位置时,让它再次开始它的路径(从左到右),但在下面的位置。我试图通过至少圆的直径改变它的 y 位置,到目前为止没有成功。 关于如何实现这一目标的任何见解?是让它成为动画的一部分更好,还是让左右移动成为一个简单的循环,最后改变 y 位置? 到目前为止我的代码如下:

var canvas3 = document.getElementById("canvas3");

canvas3.width = 300;
canvas3.height = 500;

var c3 = canvas3.getContext("2d");

var radius = 13;
var x = radius;
var y = radius;

var dx = 1;
var dy = 0;

function animate3() {
  requestAnimationFrame(animate3);

  c3.clearRect(0, 0, 300, 500);

  if (x + radius > 300 || x - radius < 0) {
    dx = 0;
    y + y;
  }

  if (y + radius > 500 || y - radius < 0) {
    dy = 0;
  }

  x += dx;
  y += dy;

  c3.beginPath();
  c3.arc(x, y, 12, 0, Math.PI * 2, false);
  c3.stroke();
  c3.fillText(5, x - 3, y + 3);
}

animate3();

我会简单地重置 x 位置并增加 y 位置:

var canvas3 = document.getElementById("canvas3");

canvas3.width = 300;
canvas3.height = 500;

var c3 = canvas3.getContext("2d");

var radius = 13;
var x = radius;
var y = radius;

var dx = 5;
var dy = 0;

function animate3() {
  requestAnimationFrame(animate3);

  c3.clearRect(0, 0, 300, 500);

  if (x + radius > 300 || x - radius < 0) {
    x = radius;
    y += radius;
  }

  if (y + radius > 500 || y - radius < 0) {
    y = radius;
  }

  x += dx;
  y += dy;

  c3.beginPath();
  c3.arc(x, y, 12, 0, Math.PI * 2, false);
  c3.stroke();
  c3.fillText(5, x - 3, y + 3);
}

animate3();
<canvas id="canvas3"/>