javascript 创建对象怪异行为[重复]

5us2dqdw  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(105)
    • 此问题在此处已有答案**:

Why does the Canvas API fill parts of these paths within a loop with the wrong color?(1个答案)
19小时前关门了。
最后一个对象决定了其他对象的颜色。当我检查画布时,我有3个绿色的正方形,因为最后一个创建的对象是绿色的,它应该是3个不同颜色的正方形。
行为

<canvas id="myCanvas" width="480" height="320"></canvas>
<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");

  class GameObject {
    constructor(x, y, w, h, color) {
      this.x = x;
      this.y = y;
      this.w = w;
      this.h = h;
      this.color = color;
    }

    drawObject() {
      ctx.rect(this.x, this.y, this.w, this.h);
      ctx.fillStyle = this.color;
      ctx.fill();
    }
  }

  bluesquare = new GameObject(0, 0, 50, 50, "blue");
  bluesquare.drawObject();
  redsquare = new GameObject(50, 0, 50, 50, "red");
  redsquare.drawObject();
  greensquare = new GameObject(100, 0, 50, 50, "green");
  greensquare.drawObject();
  
</script>
<style>
  * {
    padding: 0;
    margin: 0;
  }

  canvas {
    background: rgb(167, 167, 167);
    display: block;
    margin: 0 auto;
  }
</style>

我试着修改构造函数参数等,但仍然有同样的问题。

7kqas0il

7kqas0il1#

您在开始时错过了一个ctx.beginPath();呼叫:
Canvas 2D API的CanvasRenderingContext2D.beginPath()方法通过清空子路径列表来启动新路径。要创建新路径时,请调用此方法。

drawObject() {
  ctx.beginPath();
  ctx.rect(this.x, this.y, this.w, this.h);
  ctx.fillStyle = this.color;
  ctx.fill();
}

https://jsfiddle.net/wm1pxkfd/

相关问题