Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Can';不能在画布上移动一个圆圈吗?_Javascript_Canvas - Fatal编程技术网

Javascript Can';不能在画布上移动一个圆圈吗?

Javascript Can';不能在画布上移动一个圆圈吗?,javascript,canvas,Javascript,Canvas,这是我的代码。我不知道为什么圆圈不动。它只是停留在我所说的x和y坐标的位置 class Circle { constructor(x, y, r, clr) { this.radius = r; this.x = x; this.y = y; this.clr = clr; ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI); ctx.fillStyle = this.clr; ctx.fill(); ctx.c

这是我的代码。我不知道为什么圆圈不动。它只是停留在我所说的x和y坐标的位置

class Circle {
constructor(x, y, r, clr) {
this.radius = r;
this.x = x;
this.y = y;
this.clr = clr;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
ctx.fillStyle = this.clr;
ctx.fill();
ctx.closePath();
}

move(finalx, finaly) {
  this.finalx = finalx;
  this.finaly = finaly;

  while (this.finalx != this.x && this.finaly != this.y) {
    this.x += 2;
    this.y += 2;
 }

}
}

var x = new Circle(150, 225, 50, black);
x.move(400, 25);

您需要在每次更新后重新绘制画布。你可能想要这样的东西:

class Circle {
    constructor(x, y, r, clr) {
        this.radius = r;
        this.x = x;
        this.y = y;
        this.clr = clr;
        draw();
    }

    move(finalx, finaly) {
      this.finalx = finalx;
      this.finaly = finaly;

      while (this.finalx != this.x && this.finaly != this.y) {
        this.x += 2;
        this.y += 2;
        draw();
      }
    }

    draw() {
        ctx.clearRect(0, 0, 500, 500); // Enter your specific dimensions
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
        ctx.fillStyle = this.clr;
        ctx.fill();
        ctx.closePath();
    }
}

HTML5画布不像Flash那样工作。对于画布上的动画,必须在每一帧上绘制并清除画布。请查看网上的任何教程。很好,但是调用draw方法之间的延迟会更好!