javascript - 无法让 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 个矩形。
解决方案
如果我理解正确,你需要这个:
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
推荐阅读
- c# - 使用 System.Windows.SystemParameters 不起作用(无法导入presentationframework.dll)
- reactjs - VSCode 自动导入,组件建议在 React 中不起作用,VSCode 版本 1.57.0,MacOS
- vpn - 有没有人成功地将两个freeipa系统连接到一个vpn?
- laravel - Laravel查询关系条件中的关系
- java - 当您有多个应用程序时,如何创建密钥库文件?
- java - 将对象移动到鼠标单击位置java
- typescript - 在使用类装饰器扩展 TS 中的类时,我应该如何使用扩展的类属性?
- ios - AVAudioFile 写入不起作用 Swift iOS 14
- sql - PL/SQL 提取字符之间的数字
- python - 尝试导入另一个应用程序的模型时出现 Django 模型导入错误