canvas save和restore的作用
<canvas id="physic" width="1800" height="800" style="background: #fff;position: absolute;"></canvas>
canvas是h5新增的功能,他只有一个dom节点,canvas相当于画布,通过js控制在画布上进行创造。
在我看来,canvas就是将数据通过像素的形式呈现出来。
api中有两个重要的方法,save和restore。顾名思义,save就是保存当前的状态,当前的状态对以后有影响,
而restore是重置状态,他会重置到你上次保存的状态上。
举个例子
<canvas id='canvas' width="600" height="600" style="background: #198"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save()
ctx.fillStyle='red'
ctx.scale(2, 2)
ctx.fillRect(10, 10, 150, 100) // 红色矩形
ctx.restore()
ctx.fillRect(50, 50, 150, 100) // 黑色矩形
</script>
结果如下
可以看到,第二次的矩形没有样式了,因为重置到save时的状态了所以默认黑色。
然后我们稍微修改一下
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle='blue'
ctx.save()
ctx.fillStyle='red'
ctx.scale(2, 2)
ctx.fillRect(10, 10, 150, 100)
ctx.restore()
ctx.fillRect(50, 50, 150, 100)
结果如下
很明显,之前的蓝色样式被保存下来了。即使重置后,样式依然有。
如果有多个save(),已最后一个save为准
ctx.fillStyle='blue'
ctx.save()
ctx.fillStyle='yellow'
ctx.save()