在一个画布中合并两个图像

时间:2015-10-25 15:46:37

标签: javascript jquery html5 canvas

我正在使用此代码将两个画布的数据显示到第三个画布但它无法正常工作。 我使用localstorage保存两个画布数据并将其传递给第三个画布

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//First canvas data
var img1 = loadImage(localStorage.getItem('cbdata'), main);
//Second canvas data
var img2 = loadImage(localStorage.getItem('cbdata1'), 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) {
    var img = new Image();
    img.onload = onload;
    img.src = src;
    return img;
}

1 个答案:

答案 0 :(得分:0)

您的代码有效。检查localStorage.getItem的内容是否为空。我还通过更改ctx.drawImage命令来略微修改了图像的显示:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//First canvas data
var img1 = loadImage('http://ep01.epimg.net/elpais/imagenes/2015/10/21/ciencia/1445444934_907402_1445781076_portada_normal.jpg', main);
//Second canvas data
var img2 = loadImage('http://ep01.epimg.net/economia/imagenes/2015/10/22/actualidad/1445508003_507635_1445508894_portada_normal.jpg', main);

var imagesLoaded = 0;

function main() {
    imagesLoaded += 1;

    if (imagesLoaded == 2) {
        // composite now
        ctx.drawImage(img1, 0, 0, 100, 100);

        ctx.globalAlpha = 0.5;
        ctx.drawImage(img2, 100, 0, 100, 100);
    }
}

function loadImage(src, onload) {
    console.log('loadImage', src);
    var img = new Image();

    img.onload = onload;
    img.src = src;

    return img;
}

https://jsfiddle.net/4Le4g8ta/