0

The last object determines the color of the other ones. When I check the canvas I have 3 green squares, cause the last object created is green, and it was supposed to be 3 squares with different colors.

The behavior

1

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

I tried to modify the constructor parameters and etc, but still having the same problem.

vimuth
  • 5,064
  • 33
  • 79
  • 116
  • You’re confusing [`fillRect`](//developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/fillRect) with [`rect`](//developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/rect). See [my answer](/a/69730036/4642212) which explains the differences in detail. – Sebastian Simon Dec 24 '22 at 14:47

1 Answers1

1

You were missing a ctx.beginPath(); call at the beginning:

The CanvasRenderingContext2D.beginPath() method of the Canvas 2D API starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.

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

https://jsfiddle.net/wm1pxkfd/

MorKadosh
  • 5,846
  • 3
  • 25
  • 37