I’m trying to draw two images on the same canvas, but the second image being loaded is "erasing" the first. The images are the same size and they complete each other.
HTML:
<canvas id="canvas style="width: 400px"/>
<img id="img1" src="myImage1" />
<img id="img2" src="myImage2" />
JS:
var canvas = document.getElementByID("canvas");
var ctx = canvas.getContext('2d');
var img1 = document.getElementByID("img1");
var img2 = document.getElementByID("img2");
img1.onload = function(){
canvas.width = img1.naturalWidth;
canvas.height = img1.naturalHeight;
ctx.drawImage(img1, 0, 0);
}
img2.onload = function(){
canvas.width = img2.naturalWidth;
canvas.height = img2.naturalHeight;
ctx.drawImage(img2, 0, 0);
}
2
Answers
Changing the size of the canvas clears the context.
If you’re sure the images align, all you have to do is make sure you only initialize once using the dimensions of whichever image loads first:
Alternatively, you could wait for all images to be loaded, find the largest width and height dimension, set the canvas size and only then draw all the images to it.
You can’t change height or width because canvas will be cleared
Better wait for both images to load and then set dimensions