小程序canvas生成海报保存至手机相册

小程序canvas画图保存至手机相册

(1)可直接展示生成的海报 。因手机分辨率不同可能导致生成的海报会有细微差别,这里隐藏canvas海报,页面正常设置海报样式保存时保存隐藏的canvas海报

(2)tip: canvas 组件是由客户端创建的原生组件,它的层级是最高的,不能通过 z-index 控制层级。(在手机上canvas在最上层无法隐藏)解决方法:

  canvas外加一框view 设置样式:style="0;height:0;overflow: hidden;opacity:0;position:absolute;left:-375px;top:0; 隐藏在屏幕之外

<view class="container">
    <view class="btn" bindtap="saveImage">保存图片</view>
    <view class="canvasBox">
    <!-- <view class="canvasBox" style="0;height:0;overflow: hidden;opacity:0;position:absolute;left:-375px;top:0;"> -->
   <!--这里为了展示效果为设置到屏幕之外 -->
    <canvas canvas-id='myCanvas' style='375px;height:500px;margin: 0;padding: 0;display:block;'></canvas>
  </view>
</view>

(3)绘制圆形用户头像 

      ctx.arc(46,358,25, 0, 2 * Math.PI)
      ctx.fill()
      ctx.save();
      ctx.beginPath(); //开始绘制
      ctx.clip(); //剪切
      ctx.drawImage(res.path, 23, 333, 50, 50); //userHeader // 推进去图片必须是https
      ctx.restore(); //恢复之前保存的绘图上下文 继续绘制
(4)小程序canvas真机绘图时无法使用网络图片,需下载至手机使用临时路径绘制,这里使用wx.getImageInfo获取网络图片临时路径
(5)这里图片均使用网络图片
//index.js
const app = getApp()
Page({
  data: {
    cardPath: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534766809331&di=012cc4ad15d457ffa55c6537503eb84a&imgtype=0&src=http%3A%2F%2Fpicture.5068.com%2Fallimg%2F121120%2F4-1211201G920.jpg',
    headPath: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534765039080&di=1e81a596bc89cd54db55c0dbc7c4bb87&imgtype=0&src=http%3A%2F%2Fimg3.100bt.com%2Fupload%2Fttq%2F20140529%2F1401337844678_middle.png',
    sendName: '文字描述描述文字'
  },
  onLoad: function (options) {
    var that = this;
    wx: wx.getSystemInfo({
      success: function (res) {
        that.setData({
          pixelRatio: res.pixelRatio,
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        })
      }
    })
    that.drawCanvas();
  },
  //画图
  drawCanvas: function () {
    this.setData({
      cardPath: this.data.cardPath,
      headPath: this.data.headPath,
      sendName: this.data.sendName
    });
    let ctx = wx.createCanvasContext('myCanvas');
    let ctxW = this.data.windowWidth;
    let ctxH = 1210;
    // 默认像素比
    let pixelRatio = this.data.pixelRatio;

    // 垂直渐变
    const grd = ctx.createLinearGradient(0, 0, 0, ctxH);
    grd.addColorStop(0, '#ffffff');
    grd.addColorStop(1, '#ffffff');
    ctx.setFillStyle(grd);
    ctx.fillRect(0, 0, ctxW, ctxH);

    wx.getImageInfo({
      src: this.data.cardPath,
      success: (res) => {
        ctx.drawImage(res.path, 15, 15, 345, 470); //card
        wx.getImageInfo({
          src: this.data.headPath,
          success: (res) => {
            /**/
            ctx.arc(46,358,25, 0, 2 * Math.PI)
            ctx.fill()
            ctx.save();
            ctx.beginPath(); //开始绘制
            ctx.clip(); //剪切
            ctx.drawImage(res.path, 23, 333, 50, 50); //userHeader  // 推进去图片必须是https
            ctx.restore(); //恢复之前保存的绘图上下文 继续绘制
            /**/

            ctx.setTextAlign('left');
            ctx.setTextBaseline('middle');
            ctx.setFontSize(16);
            ctx.setFillStyle('#fff');
            this.fontLineFeed(ctx, this.data.sendName, 450, 30, 79, 328);
            ctx.stroke();
            ctx.draw();
          }
        })

      }
    })
  },
  // 保存图片
  saveImage: function (e) {
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(result) {
            wx.showToast({
              title: '图片保存成功',
              icon: 'success',
              duration: 2000
            })
          }
        })
      }
    })
  },
  // 文字换行
  fontLineFeed: function (ctx, str, splitLen, strHeight, x, y) {
    let strArr = [];
    for (let i = 0, len = str.length / splitLen; i < len; i++) {
      strArr.push(str.substring(i * splitLen, i * splitLen + splitLen));
    }
    let s = 0;
    for (let j = 0, len = strArr.length; j < len; j++) {
      s = s + strHeight;
      ctx.fillText(strArr[j], x, y + s);
    }
  },
})

 (6)页面显示样式

(7)保存图片为

(8)tips:保存至手机时需配置网络图片域名至小程序开发者downloadFile 合法域名下。

   tips:微信用户头像域名也必须配置 (大坑.........)

 

 

 

原文地址:https://www.cnblogs.com/cdj61/p/9507192.html