I have two html img objects with different src urls. I'd like to combine these two images (using canvas), and create one merged img object.
Is this possible? How?
You could use drawImage. Demo. Code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img1 = loadImage('http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png', main);
var img2 = loadImage('http://introcs.cs.princeton.edu/java/31datatype/peppers.jpg', main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if(imagesLoaded == 2) {
// composite now
ctx.drawImage(img1, 0, 0);
ctx.globalAlpha = 0.5;
ctx.drawImage(img2, 0, 0);
}
}
function loadImage(src, onload) {
// http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
Adapt as needed. :)
You can draw both images on the canvas and combine them with any overlay mode you like. To get the bitmap data from the canvas you can use 'toDataURL'. Only note that both images should come from the same domain as the page, otherwise your access to the pixel data is blocked for security reasons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With