一,现象
this.context.beginPath();
this.context.moveTo(10, 10);
this.context.lineTo(10, 100);
this.context.lineTo(100, 100);
this.context.lineTo(100, 10);
this.context.lineTo(10, 10);
this.context.stroke();
本来绘制的是正方形,结果绘制出来是个矩形,边的宽度也不一样
二,原因
画布初始的宽度是300150,如果不是这个值的话,绘制的内容会被拉伸.(想象着300150画布上的内容被拉伸)
三,解决方案
微信提供了这种问题的解决方案,代码如下:
const query = wx.createSelectorQuery()
query.select('#myCanvas').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)
ctx.beginPath();
ctx.moveTo(10, 10)
ctx.lineTo(10, 100)
ctx.lineTo(100, 100)
ctx.lineTo(100, 10)
ctx.lineTo(10, 10)
ctx.stroke()
})
}
实现的效果: