javascripthtmlcanvashtml5-canvasglobalcompositeoperation

merging multiple <canvas> issue


I'm designing a simple app for which I need to use multiple globalCompositeOperation, and therefore I need to use multiple hidden items, then merge them to get the final result.

one of the canvas items is used to drawImage() and then use it as an alpha mask.

I assumed that on 2nd canvas if I use to draw 1st canvas, it will copy it exactly so I can add 2nd thing on top of it. It does copy only the fillRect() and ignores the drawImage() function...

Any idea how can I forward entire content of the first canvas to 2nd? I need the masked part to move to the 2nd canvas.

Been stuck on it for hours and need your help. Tried to use toDataUrl("image/png") and then output that into 2nd canvas, but getting same results :(

simplified version under: http://jsfiddle.net/EbVmm/17/

Thanks

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);

};

Solution

  • You are trying to use alphaObj before it is fully loaded.

    Try something like this:

    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);
    };