First step is to wrap your canvases into a container:
<div id="stack">
<canvas id="bg" width="500" height="500"></canvas>
<canvas id="lc" width="500" height="500"></canvas>
<canvas id="rc" width="500" height="500"></canvas>
<canvas id="ch" width="500" height="500"></canvas>
<div>
then properly apply CSS rules:
#stack {
position:relative;
}
#stack > canvas {
position:absolute;
left:0;
top:0;
}
z-index
is not necessary here as the first canvas will be at the bottom etc.
Next is to implement a image loader handler as image loading is asynchronous. This is the reason why your image doesn't show as the image hasn't finished loading before calling drawImage()
(at the time the code gets to the "fourth" element the image may be loaded depending on various factors such as cache, system performance etc - but this is in the category "random result":
var bg = document.getElementById('bg').getContext('2d'),
lc = document.getElementById('lc').getContext('2d'),
rc = document.getElementById('rc').getContext('2d'),
ch = document.getElementById('ch').getContext('2d'),
img = new Image();
img.onload = drawImgs; /// set handler
img.src = "image.png"; /// set url
function drawImgs() {
/// 'this' is the loaded image
bg.drawImage(this, 0,0);
lc.drawImage(this, 64,64);
rc.drawImage(this, 128,128);
ch.drawImage(this, 192,192);
/// continue rest of code here...
}
If you put your script at the bottom of your page then that's it. If in the header wrap your script in:
window.onload = function() {
... code above here...
}
Other considerations is that your image gets loaded properly. For that you can use the onerror
and onabort
handlers on the image object:
img.onerror = functionToHandleError;
img.onabort = functionToHandleAbort;
also these defined before setting the src
property.