最近在看微信小程序canvas的功能,突然发现save和restore的用法,官方文档介绍的比较少,自己做了一个demo进行测试实现:
- index.wxml文件
<!--index.wxml-->
<view class="container">
<canvas canvas-id="mycanvas" style="height:1000px;width:375px"></canvas>
</view>
- index.js文件
Page({
data: {
},
onReady() {
this.ctx = wx.createCanvasContext('mycanvas', this)
this.painting()
},
painting() {
this.ctx.fillRect(10,10,100,100)
this.ctx.save()
this.ctx.setFillStyle('red')
this.ctx.scale(2,1)
this.ctx.fillRect(10,200,50,50)
this.ctx.restore()
this.ctx.setFillStyle('blue')
this.ctx.fillRect(50,50,50,50)
this.ctx.draw()
}
})
1.绘画红色块之前进行了save()操作,结果如下:
2.绘画红色块的时候不进行save()操作,结果如下:(将sava()注释)
3.结果分析:
(1)可以从来个结果分析,save()保存了之前的所有操作,restore()获取了之前的保存的状态,从文档上看,目前只能获取上次保存的状态;
(2)为什么要进行保存呢,我们看到,假设我们的需求只是想让红色块进行scale操作,如果在操作红色块的时候进行保存,那么蓝色块也会进行scale的操作。然后进行restore方法,可以获取save之前的状态,做到只改变红色块,而不改变蓝色块。
(3)温馨提示:scale,setfillstyle等操作一定要在fillrect之前,不然不显示出来。