【问题标题】:merging multiple <canvas> issue合并多个 <canvas> 问题
【发布时间】:2013-11-05 18:01:25
【问题描述】:

我正在设计一个简单的应用程序,我需要使用多个globalCompositeOperation,因此我需要使用多个隐藏项,然后将它们合并以获得最终结果。

其中一个画布项用于drawImage(),然后将其用作 alpha 蒙版。

我假设在第二个画布上,如果我用来绘制第一个画布,它会完全复制它,所以我可以在上面添加第二个东西。它只复制 fillRect() 并忽略 drawImage() 函数...

知道如何将第一个画布的全部内容转发到第二个吗?我需要蒙面部分移动到第二个画布。

坚持了几个小时,需要您的帮助。尝试使用 toDataUrl("image/png") 然后将其输出到第二个画布,但得到相同的结果:(

简化版如下: http://jsfiddle.net/EbVmm/17/

谢谢

var c1 = document.getElementById("canvas1");
var c2 = document.getElementById("canvas2");

function drawScene(mainColour) {

    var ctx = c1.getContext("2d");

    var alphaPath = "http://eskarian.com/images/alpha-test.png";
    var alphaObj = new Image();
    alphaObj.src = alphaPath;

    ctx.fillStyle = mainColour;
    ctx.fillRect(0, 0, 200, 300);
    ctx.globalCompositeOperation = 'xor';
    alphaObj.onload = function () {
        ctx.drawImage(alphaObj, 0, 0);
    };
};

function addScene(colour) {
    var ctx2 = c2.getContext("2d");

    ctx2.drawImage(c1, 0, 0);
    ctx2.globalCompositeOperation = "source-over";
    ctx2.fillStyle = colour;
    ctx2.fillRect(50, 50, 100, 100);

};

【问题讨论】:

    标签: javascript html canvas html5-canvas globalcompositeoperation


    【解决方案1】:

    您正在尝试在 alphaObj 完全加载之前使用它。

    试试这样的:

    var c1 = document.getElementById("canvas1");
    var c2 = document.getElementById("canvas2");
    
    var alphaPath = "http://eskarian.com/images/alpha-test.png";
    var alphaObj = new Image();
    alphaObj.onload = function () {
        drawScene(mainColour);
        addScene(colour)
    };
    alphaObj.src = alphaPath;
    
    
    function drawScene(mainColour) {
        var ctx = c1.getContext("2d");
        ctx.drawImage(alphaObj, 0, 0);
        ctx.fillStyle = mainColour;
        ctx.fillRect(0, 0, 200, 300);
        ctx.globalCompositeOperation = 'xor';
    };
    
    function addScene(colour) {
        var ctx2 = c2.getContext("2d");
        ctx2.drawImage(c1, 0, 0);
        ctx2.globalCompositeOperation = "source-over";
        ctx2.fillStyle = colour;
        ctx2.fillRect(50, 50, 100, 100);
    };
    

    【讨论】:

    • 谢谢,做这么简单的事情-.- 在解决方案如此简单的时候想太多了 :) 顺便说一句,我只需要在您的代码中做一点小改动。 ctx.drawImage(alphaObj, 0, 0); 需要在 ctx.globalCompositeOperation = 'xor'; 之后才能使 alpha 正常工作。除此之外,它就像一个魅力:)
    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多