Reputation: 465
I'm working on building my first mini JS game and working through the w3schools tutorial but can't even get my first component to load in the codepen preview area. This has been a very disappointing first couple steps. I know myGameArea loads fine as it's styled to pop but I just want a simple red square to draw on top of it.
var myGamePiece;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function(){
this.context.clearRect(0,0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.update = function(){
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function updateGameArea() {
myGameArea.clear();
myGameArea.update();
}
<button onClick="startGame()">
Press
</button>
Upvotes: 2
Views: 325
Reputation: 10508
updateGameArea
calls myGameArea.clear()
and then tries to call update
which doesn't exist. Are you not getting an error when this runs?
You probably want to call myGamePiece.update()
.
Upvotes: 2