I’m having an issue with a game that I’m trying to make. Here is my code (very basic):
var canvas = document.createElement("canvas");
var gameCanvas = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
// Global variables
var game;
game.fps = 60;
game._intervalId = setInterval(game.run, 1000 / game.fps);
// Game loop
game.run = function() {
game.draw();
};
// Functions
game.draw = function() {
// Background image
var bgImage = new Image();
bgImage.src = "img/background.png";
// Player image
var playerImage = new Image();
playerImage.src = "img/player.png";
// Draw
gameCanvas.drawImage(bgImage, 0, 0);
gameCanvas.drawImage(playerImage, 10, 10);
}
// Game over
document.getElementById('end').onclick = function stop(){
clearInterval(game._intervalId);
}
// Run
window.onload = game.run();
The game doesn’t run properly. Have I done anything wrong, or is there something I have missed out? Here is a link to the page: http://dl.dropbox.com/u/33213779/Game/demo_me.html
Thanks.
There are two issues that I can spot from what you are writing.
First one would be that you have to init your game-variable as an object:
The second issue would be that you are not preloading your image sources (instead you are loading them 60 times each seconds….) so that the canvas is not able to access them as they are still being loaded.
Instead you could use a mechanism like this:
Note that this is extremely oversimplified as image preloading is an area stricken with a lot of pitfalls. But I guess you’ll get the idea.
By the way this is a really good tutorial on game logic and all things canvas.