I am trying to create an Asteroids type game using JavaScript along with html5's canvas element for drawing. I have searched around and have looked at examples but I can't figure out what is wrong with my rendering that I do in the game loop that is run every frame. The problem appears to be only that the canvas is not cleared at the beginning of each frame but I feel there might be something wrong also. The code used and shown below only works in Firefox but not Google Chrome or Safari.
Here is a picture of what it renders in Chrome:
What is is supposed to look like and is in Firefox:
Here is my set up for drawing on the canvas:
Code:
var canvas = null;
var c2d = null;
//...
window.onload = init;
function init() {
canvas = document.getElementById('canvas');
c2d = canvas.getContext('2d');
setInterval( step, 1000/FPS );
//...
//c2d.setTransform(1,0,0,1,0,0); // reset to identity <--Do I need this?
}
Below is the game loop function. Am I clearing the canvas correctly because it does not clear the screen? Also am I using the save and restore functions correctly? Each asteroid and player drawn is at a different of position and rotation so am I doing it correct to draw them?
Code:
function step() {
//...
canvas.width = canvas.width; //clear canvas PROBLEM
//Things I have tried:
//canvas.height = canvas.height; //clear canvas
//c2d.clearRect(0, 0, canvas.width, canvas.height);
for (u=0;u<asteroids.length;u++) {
c2d.save();
asteroids[u].draw();
c2d.restore();
}
c2d.save();
player.draw();
c2d.restore();
c2d.strokeStyle = "#000000";
c2d.stroke();
}
Below is the Asteroid and Player drawing functions. The Asteroid is a polygon and the Player is a triangle. Both rotate and are draw correctly but should I be passing a reference to the drawing reference?