Html5 canvas 如果没有context.restore()函数,canvas elment上的多个globalCompositeOperation结果将无法工作

Html5 canvas 如果没有context.restore()函数,canvas elment上的多个globalCompositeOperation结果将无法工作,html5-canvas,Html5 Canvas,我想在画布上显示多个globalCompositeOperation结果。我通过以下方式编写代码 您的浏览器不支持HTML5 为什么我们需要恢复临时上下文? 为什么在不恢复上下文的情况下最后一个结果是正确的? 请在 <canvas id = "tempCanvas" width = "400" height = "100" style = "display: none;"> </canvas> <script> var context = docu

我想在画布上显示多个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>