canvas遇到的坑
1.文字换行
2.真机不能使用网络数据图片(真坑) 点击显示效果我就不写了,你们可以自己加一下
全部代码贴出来
css#preview {width: 100%;height: 100%;background: rgba(0, 0, 0, 0.6);position: fixed;z-index: 999;top: 0;overflow: hidden;bottom: 0;}#preview button {width: 43%;position: absolute;bottom: 218rpx;left: 28%;z-index: 5;border-radius: 37rpx;height: 66rpx;line-height: 66rpx;background: #fd5b4c;}#preview image {width: 87%;position: absolute;top: 8%;left: 6%;z-index: 3;border-radius: 19rpx;}#preview .hide1 image {width: 10%;height: 6%;position: absolute;right: 0;left: 84%;}#preview text {position: absolute;bottom: 170rpx;left: 25%;z-index: 5;font-size: 22rpx;color: gainsboro;}canvas { position: fixed;top: 0;left: 10000rpx;}wxml<canvas canvas-id="shareImg" style="width:545px;height:771px;"></canvas> <view hidden='{{hidden}}' id='preview' class="hide1{{show1?'':'show'}}"><image src='{{prurl}}' mode='widthFix'></image><button type='primary' size='mini' bindtap='save'>保存分享图</button><text>保存后,可以从手机相册分享到朋友圈</text><view class="hide1{{show1?'':'show'}}" bindtap='onTap'><image src='../../images/Close.png'></image></view></view>jsgetData() {/*商品详情接口数据代码省略*///下载图片var that = this;wx.downloadFile({ //需要小程序后台添加downloadFile域名url: res.result.product.images[0].url, //接口返回数据type: 'image', //类别success: function (res) {var _avatarPath = res.tempFilePathconst ctx = wx.createCanvasContext('shareImg');var imgPath = _avatarPath //商品图console.log(imgPath)var bgImgPath = '../../images/qrcode.jpg'; //二维码图ctx.setFillStyle('white')ctx.fillRect(0, 0, 6000, 2800);ctx.drawImage(imgPath, 120, 30, 320, 320);ctx.drawImage(bgImgPath, 40, 500, 120, 110);ctx.setFontSize(22)ctx.beginPath("")var lineWidth = 0;var canvasWidth = 300;var initHeight = 380;var lastSubStrIndex = 0;ctx.setFillStyle('black')var str = that.data.product.title //商品价格名称ctx.fillText('长按识别图中的小程序码', 190, 540)ctx.fillText('查看详情', 190, 580)//文字换行 这个地方有可能报错注释掉就可以for (let i = 0; i < str.length; i++) {lineWidth += ctx.measureText(str[i]).width;if (lineWidth > canvasWidth) {ctx.fillText(str.substring(lastSubStrIndex, i), 18, initHeight); //绘制截取部分initHeight += 34; //文字行高lineWidth = 0;lastSubStrIndex = i;}if (i == str.length - 1) {//绘制剩余部分ctx.fillText(str.substring(lastSubStrIndex, i + 1), 18, initHeight);}}ctx.setFillStyle('red')ctx.fillText(that.data.product.price, 460, 380) //that.data.product.price 商品价格数据ctx.setStrokeStyle('gainsboro')ctx.strokeRect(20, 450, 510, 0.1)ctx.stroke()ctx.draw()}})
}