对于微信小程序,canvas处理过程当中,dramImage默认图片引用是有残缺的javascript
打开连接(原官网例子),浏览器唤醒微信开发这工具,打开链接以前须要下载好微信开发者工具,如已安装则直接唤起,没有则会提示下载css
经过对canvas绘图过程的修改,或者其样式的修改,达到彻底显示,并自适应不一样机型的目的java
Page({ data:{ imgSrc: '', // 须要处理图片地址 imgW: '', // canvas 宽度 imgH: '', // canvas 高度 byclear: 1 // 比例,这里将iphon6- 375像素设置为1标准,以便在自适应上的转换 }, onReady() { var that = this // 根据屏幕的宽度计算标准比例值。这里讲375做为标准值 wx.getSystemInfo({ success: function(res) { let byclear = res.screenWidth / 375 that.setData({ byclear }) }, }) }, openAndDraw() { // 选择图片 var that = this wx.chooseImage({ success: (res) => { that.setData({ imgSrc: res.tempFilePaths[0], res }) } }) }, checkwh(e) { // 处理逻辑 } })
默认canvas 是没法获取图片的高度的,再者小程序里面没有 new Image()这个方法,只能经过标签组件image间接获取,因此咱们须要在wxml中插入一个隐藏的标签image,隐藏方法咱们设置display:none
或者hidden
就能够了,注意不要wx:if
, wx:if
不会触发bindload事件。canvas
<image src="{{imgSrc}}" bindload='checkwh' mode='widthFix' hidden/> <canvas canvas-id="canvasIn" class="canvas"></canvas>
在方法checkwh里面便可获取到图片宽高小程序
checkwh(e){ // 实际宽度 e.detail.width 高度 e.detail.height let whsrc = e.detail.height / e.detail.width // 计算高宽,须要处理图片宽度小于屏幕宽度的时候 对应的canvas比例 }
dramImage
绘图方法,咱们能够经过对画布的放大缩小scale
来完整绘制,继续在checkwh中进行处理.scale缩放比例很简单,咱们只要计算出屏幕与图片的实际比例,对应缩小就可。即:375 * byclear / e.detail.width
这里要带上自适应比例,固然对于图片宽度小于屏幕的咱们不作缩放处理微信小程序
checkwh(e){ // 实际宽度 e.detail.width 高度 e.detail.height let whsrc = e.detail.height / e.detail.width // 计算高宽,须要处理图片宽度大于屏幕宽度的时候 对应的canvas比例 let res = this.data.res let byclear = this.data.byclear const ctx = wx.createCanvasContext('canvasIn', this); // 对画布进行缩放,注意scale两个参数保持一致,即缩放比例都是同样的。保证宽高比一致 if (e.detail.width > 375 * byclear) ctx.scale(375 * byclear / e.detail.width, 375 * byclear / e.detail.width); ctx.drawImage(res.tempFilePaths[0], 0, 0, e.detail.width, e.detail.height) ctx.draw() // 后续操做 }
上面咱们已经完整的将图片绘制到canvas中了,还不够,下面咱们将设置设置canvas宽高大小,已达到彻底展现浏览器
<canvas canvas-id="canvasIn" class="canvas" style="width:{{imgW}}rpx;height:{{imgH}}rpx;margin:0 auto;"> </canvas>
微信自适应单位是rpx,对于iphone 6 ,375px = 750rpx => 1px = 2rpx; 其余型号计算是带上比例byclear
便可,而后图片小于屏幕宽度,不作处理,checkwh后续代码
所以:微信
checkwh(e){ // 前面代码... this.setData({ imgW: e.detail.width > 375 ? 750 : e.detail.width * 2 / byclear, imgH: e.detail.width > 375 ? 750 * whsrc : e.detail.height * 2 / byclear }) }
zoom方案对比scale方案,比较好的地方在于,不用计算canvas的大小,也不用缩放比例,直接将原图的宽高设置成canvas的宽高,而后,经过zoom对canvas进行缩放,直接放代码额,这里的缩放比例,即为 图片宽度 / 750
,注意这里不须要比例计算,css样式会自动进行样式比率计算
关键wxml代码微信开发
<canvas canvas-id="canvasIn" class="canvas" style="width:{{imgW}}rpx;height:{{imgH}}rpx;margin:0 auto;zoom:{{imgW > 750 ? 750 / imgW : 1}}"></canvas>
关键js代码iphone
checkwh(e){ var vhsrc = e.detail.height / e.detail.width let res = this.data.res let byclear = this.data.byclear const ctx = wx.createCanvasContext('canvasIn', this); ctx.drawImage(res.tempFilePaths[0], 0, 0, e.detail.width, e.detail.height) ctx.draw() this.setData({ imgW: e.detail.width * 2 / byclear, imgH: e.detail.height * 2 / byclear }) },