Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas - Combing two images, return one img html object?

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?

like image 459
Pauly Dee Avatar asked Sep 02 '11 11:09

Pauly Dee


2 Answers

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. :)

like image 168
Juho Vepsäläinen Avatar answered Sep 21 '22 14:09

Juho Vepsäläinen


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.

like image 39
Variant Avatar answered Sep 23 '22 14:09

Variant