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