Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 446
Sail edited this page Jun 21, 2018
·
1 revision
原因
相关文章:Canvas 绘图模糊问题解析
在web端,可以通过canvas的width、height属性来改变canvas的上下文宽高,放大devicePixelRatio(设备像素比)倍来实现高清晰度。
而在小程序端,canvas组件不能自由设置上下文的宽高,所以暂时无法在一块画布上实现高清晰度的绘制。
解决方案
在非可视区域另建一块canvas画布,用于生成图片。裁剪图片时,记录图片在原画布的坐标位置(imgLeft、imgTop)、大小(scaleWidth、scaleHeight)、裁剪区域(cut.x、cut.y、cut.width、cut.height),并同比放大devicePixelRatio倍绘制到非可视区域的canvas画布中,调用小程序原生生成图片方法wx.canvasToTempFilePath进行裁剪
Page({// ...btnHandle(){// 点击了裁剪按钮let{ imgLeft, imgTop, scaleWidth, scaleHeight }=this.wecropper// 获取图片在原画布坐标位置及宽高let{ x, y, width, height }=this.wecropper.cut// 获取裁剪框位置及大小// 所有参数乘设备像素比imgLeft=imgLeft*devicePixelRatioimgTop=imgTop*devicePixelRatioscaleWidth=scaleWidth*devicePixelRatioscaleHeight=scaleHeight*devicePixelRatiox=x*devicePixelRatioy=y*devicePixelRatiowidth=width*devicePixelRatioheight=height*devicePixelRatioconsttargetCtx=wx.createCanvasContext('target')// 这里是目标canvas画布的id值targetCtx.drawImage(tmp,imgLeft,imgTop,scaleWidth,scaleHeight)// tmp代表被裁剪图片的临时路径wx.canvasToTempFilePath({canvasId: 'target',
x,
y,
width,
height,success(res){consttmpPath=res.tempFilePathconsole.log(tmpPath)}})}})