1

我想在画布上显示多个 globalCompositeOperation 结果。我按照您的浏览器不支持 HTML5 编写了代码

<canvas id = "tempCanvas" width = "400" height = "100" style = "display: none;">
</canvas>

<script>
    var context = document.getElementById("canvas").getContext("2d");
    var tempContext = document.getElementById("tempCanvas").getContext("2d");

    var offset = 10;
    var operationValues = new Array();

    operationValues.push("source-atop");
    operationValues.push("source-in");
    operationValues.push("source-out");
    operationValues.push("source-over");

    for (var i = 0; i < operationValues.length; i++) {
        tempContext.save();
        tempContext.clearRect(0, 0, 400, 100);

        //draw destination rectangle
        tempContext.beginPath();
        tempContext.rect(10, 10, 50, 50);
        tempContext.fillStyle = 'red';
        tempContext.fill();

        tempContext.globalCompositeOperation = operationValues[i];

        //draw source rectangle
        tempContext.beginPath();
        tempContext.rect(40, 40, 50, 50);
        tempContext.fillStyle = 'green';
        tempContext.fill();

        /*
         *the result will be incorrect 
         *if you remove tempContext.restore() function
        */
        tempContext.restore();

        context.drawImage(document.getElementById("tempCanvas"), 0, 0);
        context.translate(100, 0);
    }
</script>

为什么我们需要恢复 tempContext?
为什么在不恢复 tempContext 的情况下最后一个结果是正确的?在http://jsfiddle.net/thepyaethuaung/pcNvA/3/
上查看

4

0 回答 0