It is hard to say where exactly it flickers without looking at the whole solution, but I would blame setInterval()
. The way to go is to use requestAnimationFrame
technique described here: http://www.html5canvastutorials.com/advanced/html5-canvas-animation-stage/
I was able to achieve very smooth animations by using this code template:
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function animate() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// update
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
// draw stuff
// request new frame
requestAnimFrame(function() {
animate();
});
}
animate();
In general, setInterval()
is fairly bad, use setTimeout()
after each re-draw, since interval might come at the worst timing possible.
Note, depending on required browser versions support, you might want to drop setTimeout alltogether, as requestAnimationFrame is universally supported by now.
Update A simple fix for the image loading without using extra tools within the code would be this, although it might run some animation cycles until all images will be loaded:
function Item(.. imgSrc) {
...
this.img = new Image();
this.imgSrc = imgSrc;
var self = this;
this.loaded = false;
img.onload = function() { self.loaded = true; }
//this function draws the image to the canvas
this.draw = function() {
if (this.loaded)
gameController.ctx.drawImage(this.img, this.x, this.y);
};