Canvas - Compress two images, return a single img html object?

I have two html img objects with different src urls. I would like to combine these two images (using the canvas) and create one merged img object.

Is it possible? How?

+7
source share
3 answers

You can draw both images on the canvas and combine them with any blending mode that you like. To get raster data from the canvas, you can use 'toDataURL'. Please note that both images must come from the same domain as the page, otherwise your access to the pixel data will be blocked for security reasons.

+5
source

You can use drawImage . Demo The 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 if necessary. :)

+18
source
0
source

All Articles