How to draw multiple images to a single canvas?

Member

by deron , in category: Javascript , a month ago

How to draw multiple images to a single canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , a month ago

@deron 

To draw multiple images to a single canvas in HTML5, you can do the following:

  1. Create an HTML5 canvas element in your HTML file:
1
<canvas id="myCanvas" width="800" height="600"></canvas>


  1. Get a reference to the canvas element in your JavaScript file:
1
2
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");


  1. 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);
};


  1. 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);
    }
};


  1. Remember to handle any errors that may occur while loading the images.