微信小程序 使用canvas 绘制图文 分享卡片, 保存在手机相册

544 阅读2分钟
  • 所需变量
  var lineHeight=50;
  var lineNum=0;
  • 通过每行的文字的个数来获取文字的高度
getData: function () {
      var that = this;
      var i = 0;
      var lineNum = 1;
      var thinkStr = '';
      var thinkList = [];
      var lineWidth = 0;

      for (let item of that.data.name) {

         if (item === '\n') {
            thinkList.push(thinkStr);
            thinkList.push('a');
            i = 0;
            thinkStr = '';
            lineNum += 1;
         } else if (i === 20) {
            thinkList.push(thinkStr);
            i = 1;
            thinkStr = item;
            lineNum += 1;
         } else {
            thinkStr += item;
            i += 1;
         }
      }
      thinkList.push(thinkStr);
      console.log('lineNum==' + lineNum)
      that.setData({
         thinkList: thinkList,
         lineNum: lineNum
      });
   },
  • 使用wx.getImageInfo方法把图片下载到本地
 wx.getImageInfo({
		 // 图片路径
         src: productQr[0].img,
         success: function (res) {
            console.log(res)
            that.setData({
               imgHeight: 750,
               imgWidth: 750,
            });

            var contentHeight = lineNum * that.data.lineHeight + imgHeight + 496;
            console.log(contentHeight + '---contentHeight');
            // 填充背景色
            that.drawCanvas(ctx, contentHeight);
            // 填充背景色
            that.drawSquare(ctx, contentHeight);
            that.setData({ contentHeight: contentHeight });
			// 放大图 
            ctx.drawImage(res.path, 0, 0, imgWidth, imgHeight);

            // 价格
            that.drawFontPrice(ctx, '¥' + that.data.discountPrice > 0 ? that.data.discountPrice : that.data.goodsPrice, imgHeight + 60);
            // 图片的高度+价格与图片的间距
            var height = 875;
            // 衣服名称
            var str = that.data.name;
            // 名称的宽度
            var lineWidth = 0;
             //截取的字符串的索引值
            var lastIndex = 0;
			
			// 文字超出指定宽度自动换行
            for (let i = 0; i < str.length; i++) {
	            // ctx.measureText 返回包含指定文本宽度的对象
               lineWidth += ctx.measureText(str[i]).width;
               // 超出宽度截取, 绘制到canvas上
               if (lineWidth > 760) {
                  that.drawFont(ctx, str.substring(lastIndex, i), height);
                  // 在height = 875的基础上在加上行高
                  height += that.data.lineHeight;
                  lineWidth = 0;
                  // 保存最后一个索引值, 剩余部分从 i 开始
                  lastIndex = i;
               }
               // 剩余部分再一次绘制
               if (i == str.length - 1) {
                  that.drawFont(ctx, str.substring(lastIndex, i + 1), height);
               }
            }
            that.getImage(ctx);
         }, fail(res) {
            console.log(res);
         }
      })
  • getImage(); 绘制二维码+底部文字, 调用小程序api保存出完整图
   getImage(ctx) {
      var that = this,
         productQr = that.data.productQr,
         imgWidth = that.data.imgWidth,
         imgHeight = that.data.imgHeight;

      ctx.restore();
      console.log(productQr[1].img)
      wx.getImageInfo({
         src: productQr[1].img,
         success: function (res) {
            var qrHeight = imgWidth / 3;
            // Y轴高度
            var yHeight = 880 + that.data.lineNum * that.data.lineHeight;
			// 绘制二维码图片
            ctx.drawImage(res.path, (750 - qrHeight) / 2, yHeight, qrHeight, qrHeight);
            // 底部文字
            that.drawFontDiscern(ctx, '长按二维码识别购买', yHeight + qrHeight + 46);
            // 出图
            ctx.draw(false, function () {
               setTimeout(function () {
                  wx.canvasToTempFilePath({
                     canvasId: 'myCanvas',
                     x: 0,
                     y: 0,
                     width: imgWidth,
                     height: that.data.contentHeight,
                     success: function (res) {
                        wx.hideToast()
                        // 保存在本地相册
                        setTimeout(function () {
                           wx.saveImageToPhotosAlbum({
                              filePath: res.tempFilePath,
                              success(res) {
                                 wx.hideLoading()
                                 console.log('保存图片成功回调')
                                 wx.showToast({
                                    title: '保存成功'
                                 });
                              },
                              fail(res) {
                                 wx.hideLoading()
                                 console.log('保存图片失败回调')
                                 console.log(res);
                              }
                           })
                        }, 1000)
                     },
                     fail: function (res) {
                        console.log(res)
                     }
                  })
               }, 1000);
            });
         }
      })
   }
  • 绘制背景色
  • 绘制价格
  • 绘制标题
  • 绘制底部文字
   // 背景色
   drawSquare: function (ctx, height) {
      var that = this;

      ctx.rect(0, 0, that.data.imgWidth, height);
      ctx.setFillStyle("#ffffff");
      ctx.fill();
   }

   // 价格
   drawFontPrice: function (ctx, content, height) {
      var that = this;

      ctx.setFontSize(38);
      ctx.setFillStyle("#d81e1e");
      ctx.fillText(content, 30, height);
   }

   // 标题
   drawFont: function (ctx, content, height) {
      var that = this;

      ctx.setFontSize(34);
      ctx.setFillStyle("#000000");
      ctx.fillText(content, 30, height);
   }

   // 长按二维码识别购买文字
   drawFontDiscern: function (ctx, content, height) {
      var that = this;

      ctx.setFontSize(26);
      ctx.setFillStyle("#999999");
      ctx.fillText(content, 258, height);
   }

来张效果图收尾

这里写图片描述
附上小程序api官方链接 (https://developers.weixin.qq.com/miniprogram/dev/api/canvas/reference.html)

代码仅供参考, 根据实际需求,做相对应的调整 ...