So basically I want to make an object appear on a simple HTML canvas through the class GameObject
and I can't get it done. The code compiles fine but it just doesn't appear on the screen. I assume it has to do with the variable ctx
but I'm not too sure.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
square = new GameObject(20, 40, 50, 50, "blue");
square.drawObject();
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();
}
}
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
</style>
<canvas id="myCanvas" width="480" height="320"></canvas>