我无法获得在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.');
}
}我期望看到两个矩形(一个用于保存,一个用于最后一个矩形),但是,我看到了所有5个矩形。
发布于 2019-08-15 20:33:18
如果我没理解错的话,你需要这个:
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 =画布-> 2dcontext
发布于 2019-08-15 21:59:57
请参考以下示例代码,它在我这边运行良好(使用IE 11.116.18362.0版本):
<canvas id="canvas"></canvas>
<script>
function init() {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#FA6900';
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 4;
ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';
// Save the default state
ctx.save();
//draw a rectangle
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 100, 100);
// Restore the default state
ctx.restore();
ctx.fillRect(150, 40, 100, 100);
}
init();
</script>结果如下所示:

有关画布保存和恢复的更多详细信息,请查看本文:Understanding save() and restore() for the Canvas Context
https://stackoverflow.com/questions/57508604
复制相似问题