微信小程序离屏canvas保存图片到相册并实现文本换行

wx.createOffscreenCanvas创建离屏canvas,并授权保存图片到相册

  // 保存图片到相册
  async saveImage() {
    // 创建离屏 2D canvas 实例
    const canvas = wx.createOffscreenCanvas({
      type: '2d',
      width: 718,
      height: 832
    })
    const context = canvas.getContext('2d')
    // 创建一个图片
    const image = canvas.createImage();
    context.clearRect(0, 0, 718, 832)
    // 等待图片加载
    await new Promise(resolve => {
      image.src = '/images/share-bg.png';
      image.onload = resolve
    })
    context.drawImage(image, 0, 0, 718, 832);
    let text1 = '识别或扫码,看看你能换多少?'
    context.fillStyle = "#804431";
    context.font = "42px Arial";
    context.fontWeight = 'bold'
    // context.textAlign = 'center'
    getWarpText(context, text1, 64, 462, 640, 52, 1)
    ffCanvas = canvas;
    // 获取画完后的数据
    const imgData = context.canvas.toDataURL('image/png');
    // 获取用户相册授权
    const _that = this;
    wx.getSetting({
      success(res) {
        // 如果已授权
        if (res.authSetting['scope.writePhotosAlbum']) {
          _that.onSaveImage(imgData)
          // 如果没有授权 
        } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          // 调起用户授权
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              _that.onSaveImage(imgData)
            },
            fail() {
              wx.showToast({
                title: '您没有授权,无法保存到相册',
                icon: 'none'
              })
            }
          })
          // 如果之前授权已拒绝
        } else {
          wx.openSetting({
            success(res) {
              if (res.authSetting['scope.writePhotosAlbum']) {
                _that.onSaveImage(imgData)
              } else {
                wx.showToast({
                  title: '您没有授权,无法保存到相册',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },

  // 生成图片
  onSaveImage(imgData) {
    const _this = this;
    const fs = wx.getFileSystemManager();
    const number = new Date().getTime();
    const imgFilePath = wx.env.USER_DATA_PATH + '/' + number + '.png'
    fs.writeFile({
      filePath: imgFilePath, //设置下载图片的地址
      data: imgData.slice(22), //slice(22)的目的是去掉data:image/png;base64
      encoding: 'base64',
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: imgFilePath, //设置下载图片的地址
          success: (res) => {
            wx.showToast({
              title: '保存成功',
            })
          },
          fail: () => {
            wx.showToast({
              title: '保存到相册失败',
            })
          }
        })
      }
    })
  },

文本换行,超出省略号显示


/**
 * 计算多句换行文字
 * @param: canvas canvas上下文对象
 * @param: arrText 渲染文本数组
 * @param y 渲染第一行y轴位置
 * @param gap 文字之间的上下间隔
 */
 function getWarpTextMulti(canvas, arrText, y, gap = 10) {
  for (let index = 0; index < arrText.length; index++) {
    const text = arrText[index];
    let lineArr = getWarpText(canvas, text, MARGIN_LEFT, y, MAX_WIDTH, LINE_HEIGHT)
    y += LINE_HEIGHT * lineArr.length + gap
  }
}
/**
 * 计算换行文字
 * @param canvas canvas上下文对象
 * @param text 渲染文本
 * @param x 渲染x轴位置
 * @param y 渲染第一行y轴位置
 * @param maxWidth 最大宽度
 * @param lineHeight 行高
 * @param maxLine 最大行数 超出隐藏并显示省略号 不传入则代表不限制
 */
function getWarpText(canvas, text, x, y, maxWidth, lineHeight, maxLine) {
  // 对入参的类型进行检测
  if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number' || typeof lineHeight != 'number') {
    throw new Error("参数传入出错")
  }
  //如果最大宽度未定义 默认为canvas宽度
  if (typeof maxWidth == 'undefined') {
    maxWidth = (canvas && canvas.width);
  }
  if (typeof lineHeight == 'undefined') {
    lineHeight = (canvas.canvas && parseInt(window.getComputedStyle(canvas.canvas).lineHeight)) ||
      parseInt(window.getComputedStyle(document.body).lineHeight)
  }
  let arrText = text.split('');
  let line = '';
  let lines = [];
  let lastLine = ""
  let ellipsis = canvas.measureText("...");
  let ellipsisWidth = ellipsis.width;
  for (let n = 0; n < arrText.length; n++) {
    //每个循环累加字符
    let testLine = line + arrText[n];
    //检测累加字符 获取累加字符的高度和宽度
    let metrics = canvas.measureText(testLine);
    let testWidth = metrics.width;
    let lineWidth = canvas.measureText(line).width;

    // 如果当前添加行是最后一行 则替换最后一个字符为"..." 判断长度是否需要删去最后一个字符
    if (maxLine && maxLine - 1 === lines.length && ((lineWidth + ellipsisWidth) > maxWidth)) {
      line = line.slice(0, line.length - 1) + "...";
      testWidth = lineWidth + ellipsisWidth;
    }
    //如果累加字符的宽度大于定义的绘制文本最大宽度 则绘制累加字符的文本 并且设置换行间距再次进行绘制
    if (testWidth > maxWidth && n > 0) {
      lastLine = line;
      lines.push({
        text: line,
        x: x,
        y: y
      })
      if (maxLine && maxLine <= lines.length) {
        break
      }
      line = arrText[n];
      y += lineHeight;
    } else {
      line = testLine;
    }
  }
  if (lastLine !== line) {
    lines.push({
      text: line,
      x: x,
      y: y
    })
  }
  for (let i = 0; i < lines.length; i++) {
    const item = lines[i];
    canvas.fillText(item.text, item.x, item.y);
  }
  return lines;
}

/**
 *  绘制圆角矩形
 * @param ctx canvas上下文对象
 * @param x 渲染x轴位置
 * @param y 渲染第一行y轴位置
 * @param width 宽度
 * @param height 高
 * @param radius 
 * @param color 颜色
 * */
function roundedRect(ctx, x, y, width, height, radius, color) {
  ctx.strokeStyle = color;
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.lineTo(x + width - radius, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius); // 右上圆角
  ctx.lineTo(x + width, y + height - radius);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); // 右下圆角
  ctx.lineTo(x + radius, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius); // 左下圆角
  ctx.lineTo(x, y + radius);
  ctx.quadraticCurveTo(x, y, x + radius, y); // 左上圆角
  ctx.stroke();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容