HTML2Canvas combine 2 captured canvases into one

走远了吗. 提交于 2019-12-05 12:55:21

This function accepts two parameters top and bottom. Both are expected to be ImageData objects, which you can get via ctx.getImageData(). The bottom ImageData is returned with the top data merged unto it. This function is using the Porter-Duff method to merge colors.

function mergeData(top, bottom){
    var tD = top.data,
        bD = bottom.data,
        l = tD.length;
    for(var i = 0; i < l; i += 4){
        //source alpha
        var alphaSrc = tD[i+3] / 255, //source alpha
            alphaDst = bD[i+3] / 255, //destination alpha
            alphaSrcO = 1 - alphaSrc, //(1 - x)
            alpha = alphaSrc + alphaDst * alphaSrcO; //if destination alpha is opaque
        //merge colors
        bD[i] = ((tD[i]*alphaSrc) + (bD[i]*alphaDst*alphaSrcO)) / alpha,
        bD[i+1] = ((tD[i+1]*alphaSrc) + (bD[i+1]*alphaDst*alphaSrcO)) / alpha,
        bD[i+2] = ((tD[i+2]*alphaSrc) + (bD[i+2]*alphaDst*alphaSrcO)) / alpha,
        bD[i+3] = 255*alpha;
    }
    //return bottom
    return bottom;
}

To use this function and it's returned data, do something like this:

var merged = mergeData(ctx1.getImageData(), ctx2.getImageData());
ctx2.putImageData(merged, 0, 0);

Obviously you can put the resulting data into a 3rd, hidden context if you need to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!