微信小程序自定义分享页面(canvas绘制)

256 阅读1分钟

第一步:封装方法:

function fillTextToCanvas(cxt, text, beginWidth, beginHeight) {
  const lineLength = 24;// 行高
  let item = '';
  let count = 0;
  const stringLength = text.length;
  const newText = text.split('');
  const context = cxt;
  let beginHeightNew = beginHeight;
  context.textAlign = 'left';
  for (let i = 0; i <= stringLength; i++) {
    if (count === 15) { // count一行显示多少个字
      context.fillText(item, beginWidth, beginHeightNew);
      beginHeightNew += lineLength;
      item = '';
      count = 0;
    }
    if (i === stringLength) {
      context.fillText(item, beginWidth, beginHeightNew);
      item = '';
      count = 0;
    }
    item += newText[0];
    count += 1;
    newText.shift();
  }
}
//  canvas绘制文字自动换行
function drawLongText(longText, cxt, beginWidth, beginHeight) {
  const lines = longText.split('\n');
  const linesLen = lines.length;
  const lineLength = 18;// 行高
  if (linesLen >= 0) {
    for (let t = 0; t < linesLen; t++) {
      const beginHeightNew = beginHeight + lineLength * t;
      fillTextToCanvas(cxt, lines[t], beginWidth, beginHeightNew);
    }
  }
}

// 绘制分享图片
function createSharePicUrl(self, avatar, nickname, college, content, callback) {
  const shareCtx = wx.createCanvasContext('shareCanvas', self);
  shareCtx.setFillStyle('white');
  shareCtx.fillRect(0, 0, 300, 1000);
  // 画头部个人信息
  wx.downloadFile({
    url: avatar,
    success(res) {
      const avatarWidth = 40; // 绘制的头像宽度
      const avatarHeight = 40; // 绘制的头像高度
      const avatarX = 12; // 绘制的头像在画布上的位置
      const avatarY = 15; // 绘制的头像在画布上的位置
      shareCtx.save();
      shareCtx.beginPath(); // 开始绘制
      // 先画个圆   前两个参数确定了圆心 (x,y) 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false,即顺时针
      shareCtx.arc(
        avatarWidth / 2 + avatarX,
        avatarHeight / 2 + avatarY,
        avatarWidth / 2,
        0,
        Math.PI * 2,
        false);
      shareCtx.clip();
      shareCtx.drawImage(res.tempFilePath,
        avatarX,
        avatarY,
        avatarWidth,
        avatarHeight
      ); // 推进去图片,必须是https图片
      shareCtx.restore(); // 恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
      // 画中间帖子内容
      shareCtx.setTextAlign('left'); // 文字居中
      shareCtx.setFillStyle('#333');
      shareCtx.setFontSize(13); // 文字字号:15px
      shareCtx.fillText(nickname, 64, 31, 100);
      shareCtx.setFillStyle('#999');
      shareCtx.setFontSize(12); // 文字字号:12px
      shareCtx.fillText(college, 64, 52, 100);
      shareCtx.setFillStyle('#666');
      shareCtx.setFontSize(13); // 文字字号:15px
      drawLongText(content, shareCtx, avatarX, 75 + 10);
      const rX = 50;
      const rY = 130;
      const rW = 150;
      const rH = 150;
      shareCtx.arc(
        rW / 2 + rX,// 圆心坐标x
        rH / 2 + rY,// 圆心坐标y
        rW / 2,// 半径
        0,// 起始弧度
        2 * Math.PI,// 终止弧度
        false// 弧度的方向是否逆时针
      );
      shareCtx.clip();
      shareCtx.drawImage(res.tempFilePath, rX, rY, rW, rH);
      shareCtx.draw(false, setTimeout(callback, 200));
    },
  });
}
module.exports = {
  drawLongText,
  createSharePicUrl,
};

第二步:页面使用

  • index.wxml
<canvas canvas-id="shareCanvas" class="canvasdom"></canvas>
  • index.wxss
.canvasdom {
  position: absolute;
  top: -10000px;
  left: -1000px;
  width: 300px;
  height:1000px;
  z-index: 0;
}
  • index.js
const createSharePic = require('../../utils/cavasimg');
share() {
      createSharePic.createSharePicUrl(
        this,
        'https://ifile.jydata.com/IMAGE/SCRIPT/c7khd1g82cr000810ilg.png',// 图片
        '张三',// 昵称
        '张三是颠三倒四是颠三倒四',// 简介
        '啊哒哒哒哒的沙发上发呆的点点滴滴的方式地方都是负担',// 正文
        () => {
        wx.canvasToTempFilePath({
          canvasId: 'shareCanvas',
          x: 0,
          y: 0,
          width: 250,
          height: 300,
          success: (res) => {
            console.log(res.tempFilePath);
            wx.showShareImageMenu({
              path: res.tempFilePath,
              success: res => {
                wx.showToast({
                  title: "操作成功!",
                  icon: 'none'
                })
              },
              fail: err => {
                if (err.errMsg.indexOf('deny') != -1) {
                  wx.showModal({
                    title: "温馨提示",
                    content: "需要您授权,才能保存到相册哦~",
                    showCancel: false,
                    success: modalSuccess => {
                      wx.openSetting({
                        success(settingdata) {
                          if (settingdata.authSetting['scope.writePhotosAlbum']) {
                            wx.showToast({
                              title: '获取权限成功,再次点击图片即可保存',
                              icon: 'none'
                            })
                          } else {
                            wx.showToast({
                              title: '获取权限失败,将无法保存到相册哦~',
                              icon: 'none'
                            })
                          }
                        }
                      })
                    }
                  })
                }
              },
              complete: res => {
                console.log(res);
              }
            })
            // this.setData({
            //   sharePicUrl: res.tempFilePath,
            // });
          },
        }, this);
      });
    },

image.png