最近做小程序的时候用了很多的 canvas,在 page 里面用还是挺简单的,直接像下面就可以:
const ctx = wx.createCanvasContext('myCanvas')
context.setStrokeStyle("#00ff00")
context.setLineWidth(5)
context.rect(0, 0, 200, 200)
context.stroke()
context.draw()
但是在组件里面可真是犯傻了,实际也很简单,即使很多地方容易忽略
组件中使用 canvas
- canvas 2d
这里直接贴官方代码吧,需要在组件的 ready 方法中执行,这里拿到 context 做为全局变量,后面需要绘制图形,直接使用它再修改就好,如果每次都去获取 context 会有不同大小图形重叠的现象。
注意在 wxml 里一定要加上 type = ‘2d’,不然拿到的 context 是一个 null 值。
let that = this;
let query = wx.createSelectorQuery().in(this)
query.select('#myChart2d')
.fields({
node: true,
size: true
})
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
that.setData({
width: res[0].width * dpr,
height: res[0].height * dpr,
context: ctx
})
// 画图
that.drawPieChart2d()
})
这里注意下 wx.createSelectorQuery().in(this),这个是组件中使用到的,获取 context 的方式也变成了 canvas.getContext(‘2d’) ,简单了些。
- 旧版本
const that = this;
let query = this.createSelectorQuery()
query.select('#myChart2d').boundingClientRect();
query.exec(function (rect) {
let width = rect[0].width;
let height = rect[0].height;
let context = wx.createCanvasContext('myChart2d', that)
that.setData({
width: width,
height: height,
context: context
})
// 首次进来画图
that.drawPieChart()
});
这里需要注意几点,也是把我坑了的地方:
-
使用 this 去获取节点
//wx.createSelectorQuery() this.createSelectorQuery()
-
使用 that去创建 context
//let context = wx.createCanvasContext('myChart2d') //let context = wx.createCanvasContext('myChart2d', this) let context = wx.createCanvasContext('myChart2d', that)
我在这直接传了个 this 进去,画不出图来,找了半天。。。
-
注意不能使用 tyle = '2d’字段
//<canvas type="2d" class="chart" id="myChart2d" canvas-id="myChart2d"></canvas> <canvas type="" class="chart" id="myChart2d" canvas-id="myChart2d"></canvas>
使用旧版本的 canvas 不能把 type=“2d” 加在标签里面,不然无法绘制图形,如果要使用同一个 canvas 但是使用不同版本的 API ,可以通过填空字符串实现。
结语
这里的 canvas 用法很简单,记一下吧。
end