Can you combine multiple images into a single one using JavaScript?

I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.

<img id="img1" src="https://stackoverflow.com/questions/158750/imgfile1.png">
<img id="img2" src="https://stackoverflow.com/questions/158750/imgfile2.png">
<canvas id="canvas"></canvas>

<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

canvas.width = img1.width;
canvas.height = img1.height;

context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
</script>

Or, if you want to load the images on the fly:

<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img1 = new Image();
var img2 = new Image();

img1.onload = function() {
    canvas.width = img1.width;
    canvas.height = img1.height;
    img2.src="https://stackoverflow.com/questions/158750/imgfile2.png";
};
img2.onload = function() {
    context.globalAlpha = 1.0;
    context.drawImage(img1, 0, 0);
    context.globalAlpha = 0.5; //Remove if pngs have alpha
    context.drawImage(img2, 0, 0);
};        

img1.src="https://stackoverflow.com/questions/158750/imgfile1.png";
</script>

Leave a Comment