Canvas - 合并两张图片,返回一个 img html 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7283065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:25:05  来源:igfitidea点击:

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

htmlcanvashtml5-canvas

提问by Pauly Dee

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.

我有两个具有不同 src url 的 html img 对象。我想组合这两个图像(使用画布),并创建一个合并的 img 对象。

Is this possible? How?

这可能吗?如何?

采纳答案by Variant

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.

您可以在画布上绘制这两个图像,并将它们与您喜欢的任何叠加模式结合起来。要从画布中获取位图数据,您可以使用“toDataURL”。只需要注意两个图像应该来自与页面相同的域,否则出于安全原因,您对像素数据的访问将被阻止。

回答by Juho Veps?l?inen

You could use drawImage. Demo. Code:

你可以使用drawImage演示。代码:

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

根据需要进行调整。:)