11.微信小程序之canvas生成图片并保存到手机

在小程序中,会有这样一种需求,保存某一个页面并将其分享到朋友圈。一般的做法是:将这个页面用canvas绘制出来,通过wx.canvasToTempFilePath,把当前画布指定区域的内容导出生成指定大小的图片。然后再通过wx.saveImageToPhotosAlbum,保存图片到系统相册。由用户发朋友圈,在相册中选择图片即可。

代码展示部分,只是个逻辑,直接粘贴复制不可行。

canvas.wxml

 

canvas.js


Page({

  data: {
    
    circle:'',
    canvasHeight:0,
    imageWidth: 0,
    imageHeight: 0,
    spreadBgUrl:'',
    targetSharePath: null,
    //弹窗马上去分享
    isShow: false,
    //弹窗保存图片
    showShare:false,
    //弹窗图片保存成功
    showSuccess:false
  },

  Popup() {
    var that = this;
    that.setData({
      isShow: !this.data.isShow,
    })
  },

  goToNO:function(){
    wx.navigateTo({
      url: '../advise/advise',
    })
  },
  goToSave:function(){
    var that = this;
    that.setData({
      isShow: !that.data.isShow,
      showShare: !that.data.showShare
    })
    // 下载图片,因为下载图片是异步操作,所以必须在回调里处理图片生成的动作
    wx.downloadFile({
      url: '',
      success: function (res) {
        console.log('downloadFile 下载背景图片成功,path=' + res.tempFilePath);
        that.setData({
          spreadBgUrl: res.tempFilePath
        });
        that.drawImage();
      },
      fail: function (e) {
        console.log(e);
        wx.showToast({
          title: '下载图片出错',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  closeShare:function(){
    this.setData({
      showShare: !this.data.showShare
    })
  },
  cancalSuccess:function(){
    this.setData({
      showSuccess:false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },
  
  //绘制圆角矩形
  roundRect(ctx, x, y, w, h, r) {
    ctx.save();
    if (w < 2 * r) {
      r = w / 2;
    }
    if (h < 2 * r) {
      r = h / 2;
    }
    ctx.beginPath();
    ctx.setStrokeStyle('#ffffff');
    ctx.setLineWidth(1);
    ctx.moveTo(x + r, y);
    ctx.arcTo(x + w, y, x + w, y + h, r);
    ctx.arcTo(x + w, y + h, x, y + h, r);
    ctx.arcTo(x, y + h, x, y, r);
    ctx.arcTo(x, y, x + w, y, r);
    ctx.stroke();
    ctx.closePath();
    ctx.setFillStyle('#ffffff')
    ctx.fill();
  },

  //开始绘制图片
  drawImage:function(){
    var that = this;
    console.log('in drawImage');
    const ctx = wx.createCanvasContext('myCanvas', this);
    var bgPath = that.data.spreadBgUrl;
    console.log(bgPath);
    var icon = '/image/headCoach.png';
    var share = '/image/share.png';
    var code = '/image/code.jpg'
    ctx.setFillStyle('#FFFFFF');
    ctx.fillRect(0, 0, 375, 603);
    
    //绘制背景图片
    ctx.drawImage(bgPath, 0, 0, 375,603);
    //绘制内容
    ctx.setFillStyle('#31624d');
    ctx.setFontSize(22);
    ctx.fillText('哈哈哈',30,63);
    ctx.fillText('哈哈哈',30,103);
    ctx.fillText('so easy~~~', 30, 133);
    ctx.setFontSize(12);
    ctx.fillText('啊哈哈哈哈哈',30,173);
    
    that.roundRect(ctx, 20, 402, 335, 120, 10);
    ctx.setFillStyle('#000000');
    ctx.setFontSize(16);
    ctx.fillText('啊哈哈哈哈哈',28,430);
    ctx.fillText('啊哈哈哈哈哈', 28, 455);
    ctx.drawImage(share,28,480,140,21);
    ctx.drawImage(code,250,410,100,100);
    
    ctx.draw(false,function(){
      console.log("in draw,showShare=" + that.data.showShare + ",isShow=" + that.data.isShow);
      that.saveCanvasImage();
    });
    
    console.log("after draw,showShare=" + that.data.showShare + ",isShow=" + that.data.isShow);
  },

  //转换成图片
  saveCanvasImage:function(){
    console.log("in saveCanvasImage");
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success:function(res){
        console.log("in saveCanvasImage="+res.tempFilePath);
        that.setData({
          targetSharePath: res.tempFilePath,
        })
      }
    }, this)
  },

  //保存到相册
  saveImageTap: function () {
    var that = this;
    that.requestAlbumScope();
  },

  //检测权限
  requestAlbumScope:function(){
    var that = this;
    wx.getSetting({
      success:function(res){
        if (res.authSetting['scope.writePhotosAlbum']){
          that.saveImageToPhotosAlbum();
        }else{
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success(res){
              that.saveImageToPhotosAlbum();
            },
            fail(){
              wx.showModal({
                title: '提示',
                content: '你需要授权才能保存图片到相册',
                success: function (res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success: function (res) {
                        if (res.authSetting['scope.writePhotosAlbum']) {
                          that.saveImageToPhotosAlbum();
                        } else {
                          //用户未同意保存图片权限
                        }
                      },
                      fail: function () {
                        //用户未同意保存图片权限
                      }
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },

  saveImageToPhotosAlbum:function(){
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.targetSharePath,
      success:function(){
        that.setData({
          showShare:false,
          showSuccess:true
        })
      }
    })
  },

 


})

 

你可能感兴趣的:(微信小程序)