微信小程序2.9.0及以上版本使用 canvas.getContext('2d')绘图出现异常?
微信小程序2.9.0及以上版本使用 canvas.getContext(‘2d’)绘图出现异常,高度会莫名其妙拉伸1倍,模拟器和真机均有此现象。
代码如下:
wxml
<view class="container"> <canvas id="canvas1" type="2d" style="width: 300px; height: 300px; background-color: #ffffff;"></canvas> </view> |
javscript
Page({ data: { }, onLoad: function () { wx.createSelectorQuery() .select('#canvas1') .node() .exec((res) => { this.init(res[0].node); }) ; }, init(canvas) { var _context = canvas.getContext('2d') _context.scale(1, 1); _context.strokeStyle = "#00ff00" _context.lineWidth = 1 _context.rect(0, 0, 100, 100) _context.stroke() }}) |
经分析,2.9.0版本和2.8.3版本使用SelectorQuery获取Canvas节点返回高度存在不同。
javscript
Page({ data: { }, onLoad: function () { wx.createSelectorQuery() .select('#canvas1') .node() .exec((res) => { this.init(res[0].node); }) ; }, init(canvas) { console.log('width:'+canvas.width, 'height:'+canvas.height) console.log('_width:'+canvas._width, '_height:'+canvas._height) }}) |
2.8.3版本
2.9.0版本
临时解决方法:
用SelectorQuery获取Canvas节点后,设置canvas的width和height值
Page({ data: { }, onLoad: function () { wx.createSelectorQuery() .select('#canvas1') .node() .exec((res) => { this.init(res[0].node); }); }, init(canvas) { console.log('width:' + canvas.width, 'height:' + canvas.height) console.log('_width:' + canvas._width, '_height:' + canvas._height) canvas.width = canvas._width canvas.height = canvas._height var _context = canvas.getContext('2d') _context.scale(1, 1); _context.strokeStyle = "#00ff00" _context.lineWidth = 1 _context.rect(0, 0, 100, 100) _context.stroke() }}) |
