首页 > 解决方案 > 无法让 Canvas 恢复在 IE 11 中工作

问题描述

我无法获得在 IE 11 上保存和恢复的画布示例

在用我自己的代码尝试了很多次之后,我在网上搜索了一个示例,甚至这个没有按预期工作

   function drawShape(){

        // get the canvas element using the DOM
        var canvas = document.getElementById('mycanvas');

        // Make sure we don't execute when canvas isn't supported
        if (canvas.getContext){

           // use getContext to use the canvas for drawing
           var ctx = canvas.getContext('2d');

           // draw a rectangle with default settings
           ctx.fillRect(0,0,150,150);

           // Save the default state
           ctx.save();
           alert("Check Point 1");

           // Make changes to the settings
           ctx.fillStyle = '#66FFFF'
           ctx.fillRect( 15,15,120,120);

           alert("Check Point 2");

           // Make the new changes to the settings
           ctx.fillStyle = '#993333'
           ctx.globalAlpha = 0.5;
           ctx.fillRect(30,30,90,90);

           // Restore previous state
           ctx.restore();
           alert("Check Point 3");

           // Draw a rectangle with restored settings
           ctx.fillRect(45,45,60,60);

           // Restore original state
           ctx.restore();
           alert("Check Point 4");

           // Draw a rectangle with restored settings
           ctx.fillRect(40,40,90,90);
        } else {
           alert('You need Safari or Firefox 1.5+ to see this demo.');
        }
     }

我期待看到 2 个矩形(一个用于保存,一个用于最后重新调整)但是,我看到了所有 5 个矩形。

标签: javascriptinternet-explorerdomcanvas

解决方案


如果我理解正确,你需要这个:

CanvasRenderingContext2D.prototype.clear = CanvasRenderingContext2D.prototype.clear || function(preserveTransform) {
    if (preserveTransform) {
        this.save();
        this.setTransform(1, 0, 0, 1, 0, 0);
    }

    this.clearRect(0, 0, this.canvas.width, this.canvas.height);

    if (preserveTransform) {
        this.restore();
    }
}

我正在用它来为画布内的东西制作动画,并且我正在清理和重绘。我在每次新抽奖之前都会这样做。

按如下方式使用它:

ctx.clear() // ctx = canvas -> 2dcontext


推荐阅读