微信小程序图片选择区域裁剪实现方法(2)
JS代码部分
初始加载带入上一个页面带过来的参数路径
onLoad: function (options) { var that = this; const ctx = wx.createCanvasContext('cutImg'); ctx.setGlobalAlpha(0.4) var aa = 'https://pintuanqu.oss-cn-hangzhou.aliyuncs.com/Uploads/Picture/goodsShow/20171201/5a2125fc86566.png'<br /> //获取当前屏幕宽度 var phoneW = Number(util.nowPhoneWH()[0]*90)/100; var cutH = 150; wx.getImageInfo({ src: aa, success: function (res) { var w = phoneW; var h = (phoneW/Number(res.width))*Number(res.height) ctx.save() ctx.drawImage(aa, 0, 0, w, h) ctx.restore() ctx.setFillStyle('red') ctx.fillRect(0, 0, phoneW, cutH) ctx.draw() that.setData({ canvasW:w, canvasH:h, img:aa, cutH:cutH }) } }) },
确定选择区域开始裁剪
// 点击确认裁剪图片 okCutImg:function(){ var that = this; var canvasW = that.data.canvasW; var canvasH = that.data.canvasH; var nowCutW = that.data.cutType?canvasW:that.data.nowCutW; var nowCutH = that.data.cutType?that.data.cutH:that.data.nowCutH; var cutX = that.data.cutX; var cutY = that.data.cutY; const ctx = wx.createCanvasContext('cutImg'); ctx.setGlobalAlpha(1) ctx.drawImage(that.data.img, 0, 0, canvasW, canvasH) ctx.draw() wx.canvasToTempFilePath({ x: cutX, y: cutY, width: nowCutW, height: nowCutH, destWidth: nowCutW, destHeight: nowCutH, canvasId: 'cutImg', success: function(res) { var aa = res.tempFilePath that.setData({ cutImgUrl:aa, prienFlag:false, alreay:false }) } }) },
红框根据手指移动方法
// 点击红框开始移动 canvasMove:function(e){ var that = this; var canvasW = that.data.canvasW; var canvasH = that.data.canvasH; var nowCutW = that.data.cutType?canvasW:that.data.nowCutW; var nowCutH = that.data.cutType?that.data.cutH:that.data.nowCutH var touches = e.touches[0]; var x = touches.x; var y = touches.y-(Number(nowCutH)/2); that.data.cutType?x=0:x=x-(Number(nowCutW)/2); that.setData({ cutX:x, cutY:y }) const ctx = wx.createCanvasContext('cutImg'); ctx.setGlobalAlpha(0.4) ctx.drawImage(that.data.img, 0, 0, canvasW, canvasH) ctx.setFillStyle('red') ctx.fillRect(x, y, nowCutW, nowCutH) ctx.draw() },
上方两个选择裁剪方式的按钮
等屏裁剪
//等屏裁剪 etcType:function(){ var that = this; var propor = 100; var canvasW = that.data.canvasW; var canvasH = that.data.canvasH; var cutH = that.data.cutH; var nowCutW = (Number(canvasW)*propor)/100 var nowCutH = (Number(cutH)*propor)/100 const ctx = wx.createCanvasContext('cutImg'); ctx.setGlobalAlpha(0.4) ctx.drawImage(that.data.img, 0, 0, canvasW, canvasH) ctx.setFillStyle('red') ctx.fillRect(0, 0, nowCutW, nowCutH) ctx.draw() that.setData({ nowCutW:nowCutW, nowCutH:nowCutH, cutType:true }) },
内容版权声明:除非注明,否则皆为本站原创文章。