通过 SelectorQuery 获取 Canvas 节点,绘图问题?
< canvas type = "2d" id = "canvas" style = "width: 100%; height: 500px;" ></ canvas > |
Page({ data: { }, onLoad: function () { // 通过 SelectorQuery 获取 Canvas 节点 wx.createSelectorQuery() .select( '#canvas' ) .fields({ node: true , }) .exec( this .init.bind( this )) }, init(res) { const canvas = res[0].node const ctx = canvas.getContext( '2d' ) this .drawPath(ctx) }, drawPath(ctx){ var dwidth = 800 / 80.0; var pos = Math.ceil(Math.random() * 75) + 30; for ( var i = 0; i < 80; i++) { ctx.beginPath(); ctx.moveTo((i * dwidth), pos); var pos2 = Math.ceil(Math.random() * 75) + 30; ctx.lineTo(((i + 1) * dwidth), pos2); pos = pos2; ctx.stroke(); } ctx.strokeStyle = "green" ; for ( var i = 10; i < 80; i++) { //清除后半部份继续绘制 ctx.clearRect((i * dwidth), 0, ((i + 1) * dwidth), 150); ctx.beginPath(); ctx.moveTo((i * dwidth), pos); var pos2 = Math.ceil(Math.random() * 75) + 30; ctx.lineTo(((i + 1) * dwidth), pos2); pos = pos2; ctx.stroke(); } } }) |
开发工具中显示是清晰的,在真机预览是模糊的,麻烦帮忙看一下是哪里的问题?
3 回复
要根据 dpr 设置一下 canvas 的宽高。默认宽高是 300x150,所以会变形。
const dpr = wx.getSystemInfoSync().pixelRatio canvas.width = width * dpr canvas.height = height * dpr ctx.scale(dpr, dpr) |
麻烦提供出现问题的具体机型、微信版本号、系统版本号,以及能复现问题的代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)