@deron
To draw multiple images to a single canvas in HTML5, you can do the following:
- Create an HTML5 canvas element in your HTML file:
1
|
<canvas id="myCanvas" width="800" height="600"></canvas>
|
- Get a reference to the canvas element in your JavaScript file:
1
2
|
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
|
- Load your images using the Image constructor and draw them to the canvas using the drawImage method:
1
2
3
4
5
6
7
8
9
10
11
|
var img1 = new Image();
img1.src = "image1.jpg";
img1.onload = function() {
ctx.drawImage(img1, 0, 0);
};
var img2 = new Image();
img2.src = "image2.jpg";
img2.onload = function() {
ctx.drawImage(img2, 400, 0);
};
|
- You can also draw the images at the same time using the drawImage method inside a single onload function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
var img1 = new Image();
img1.src = "image1.jpg";
var img2 = new Image();
img2.src = "image2.jpg";
var loadedImages = 0;
img1.onload = img2.onload = function() {
loadedImages++;
if (loadedImages === 2) {
ctx.drawImage(img1, 0, 0);
ctx.drawImage(img2, 400, 0);
}
};
|
- Remember to handle any errors that may occur while loading the images.