1. 程式人生 > >微信小程式生成二維碼、生成圖片、儲存圖片到本地相簿

微信小程式生成二維碼、生成圖片、儲存圖片到本地相簿

<!--畫布遮罩-->
<!--生成二維碼的畫布-->
<canvas canvas-id="myCanvas" style='width:{{ercode_canvasWidth}}px;height:{{ercode_canvasHeight}}px;left: -300rpx'/>
<view wx:if="{{modalDisplay}}" class="mask">
    <view class="modal-container">
      <view class="modal-close">
        <text bindtap="closeRejectModal">✕</text>
      </view>
      <view class="modal-text">
        <view class="canvas-box">
          <!--生成圖片的畫布-->
          <canvas canvas-id="shareCanvas" style='width:{{canvasWidth}}px;height:{{canvasHeight}}px;margin:{{canvasWidth_y}}px auto 0 auto;box-shadow:0px 7px 20px 4px rgba(143,143,143,0.29);
disable-scroll='true'></canvas>
        </view>
      </view>
      <view class="modal-button">
        <text>儲存圖片到本地相簿,分享給好友</text>
        <button  class="but" bindtap='savePic'>儲存圖片</button>
      </view>
    </view>
 </view>
var QR = require("../../utils/qrcode.js");//前端自己生成二維碼的js外掛
Page({
  data: {
    qrCodeImg: '',          //要生成的二維碼圖片連結
    qrCodeImgs: '',         //二維碼圖片
    modalDisplay: false,    //是否顯示遮罩
    postUrl: '',            //大圖
    canvasWidth: '',        //畫布寬度
    canvasHeight: '',       //畫布高度
  },

  /**生命週期函式--監聽頁面初次渲染完成*/
  onReady: function () {
    let that = this;
    wx.getSystemInfo({
      success(res) {
        let scrollHeight = res.windowHeight - 233 - 43;
        let ratio = 750 / res.windowWidth; 
        that.setData({
          scrollHeight: scrollHeight,
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
          ratio: ratio,
          ercode_canvasWidth: 98 / ratio,
          ercode_canvasHeight: 98 / ratio,
          canvasWidth: 375 / ratio,
          canvasHeight: 670 / ratio,
          canvasWidth_y: 50 / ratio
        });
      }
    });
  },

  //分享按鈕
  showQrcode: function () {
    console.log("點選了分享,分享連結", this.data.qrCodeImg)
    wx.showLoading({
      title: '分享圖片生成中...',
      icon: 'loading'
    })
    this.setData({
      modalDisplay: true
    })
    var size = this.setCanvasSize();//動態設定畫布大小
    var qrUrl = this.data.qrCodeImg;
    if (qrUrl!==''){
      this.createQrCode(qrUrl, "myCanvas", size.w, size.h);
    }
  },

  //適配不同螢幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      size.w = this.data.ercode_canvasWidth;
      size.h = this.data.ercode_canvasHeight;
    } catch (e) {
      //console.log("獲取裝置資訊失敗" + e);
    }
    return size;
  },

  //生成二維碼
  createQrCode: function (url, canvasId, cavW, cavH) {
    //呼叫外掛中的draw方法,繪製二維碼圖片
    QR.api.draw(url, canvasId, cavW, cavH);
    setTimeout(() => { this.canvasToTempImage(); }, 1000);
  },

  //獲取臨時快取照片路徑,存入data中
  canvasToTempImage: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        that.setData({
          qrCodeImgs: tempFilePath//二維碼圖片
        });
        that.savePoster()
      },
      fail: function (res) {
        //console.log(res);
      }
    });
  },

  //大畫布
  savePoster: function () {
    var that = this;
    //console.log("儲存圖片,二維碼圖片", that.data.qrCodeImg)
    let promise1 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: that.data.qrCodeImgs,
        success: function (res) {
          console.log("二維碼", res)
          resolve(res);
        }
      })
    });
    let promise2 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: 'https://carimg/car_contain.png',
        success: function (res) {
          console.log("車", res)
          resolve(res);
        }
      })
    });
    let promise3 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: 'https://carimg/white_bg.png',
        success: function (res) {
          console.log("白色漸變", res)
          resolve(res);
        }
      })
    });
    let promise4 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: 'https://carimg/logo.png',
        success: function (res) {
          console.log("logo", res)
          resolve(res);
        }
      })
    });
    let promise5 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: 'https://carimg/50logo.png',
        success: function (res) {
          console.log("G50logo", res)
          resolve(res);
        }
      })
    });
    let promise6 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: 'https://carimg/title_icon.png',
        success: function (res) {
          console.log("標題icon", res)
          resolve(res);
        }
      })
    });
    let promise7 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: 'https://carimg/line_bottom.png',
        success: function (res) {
          console.log("藍色線", res)
          resolve(res);
        }
      })
    });
    Promise.all([
      promise1, promise2, promise3, promise4, promise5, promise6, promise7
    ]).then(res => {
      console.log(res)
      /* 圖片獲取成功才執行後續程式碼 */
      var canvas = wx.createCanvasContext('shareCanvas')
      let canvasWidth = that.data.canvasWidth,
          canvasHeight = that.data.canvasHeight,
          ercode_canvasWidth = that.data.ercode_canvasWidth,
          ercode_canvasHeight = that.data.ercode_canvasHeight,
          ercode_x = 30 / this.data.ratio,
          ercode_y = canvasHeight - (185 / this.data.ratio),
          txt_x = ercode_canvasWidth + (50 / this.data.ratio),
          txt1_y = canvasHeight - (140 / this.data.ratio),
          txt2_y = canvasHeight - (110 / this.data.ratio),
          logo_x = 15 / (this.data.ratio),
          logo_y = 15 / (this.data.ratio),
          logo_w = 69.5 / (this.data.ratio),
          logo_h = 12.5 / (this.data.ratio),
          g50logo_x = 35 / (this.data.ratio),
          g50logo_y = 72.5 / (this.data.ratio),
          g50logo_w = 140 / (this.data.ratio),
          g50logo_h = 53 / (this.data.ratio),
          g50title_x = 30 / (this.data.ratio),
          g50title_y = 104 / (this.data.ratio),
          g50title_w = 326 / (this.data.ratio),
          g50title_h = 108 / (this.data.ratio),
          white_bg_y = 244 / (this.data.ratio),
          car_contain_y = 201 / (this.data.ratio),
          car_contain_w = 375 / (this.data.ratio),
          car_contain_h = 233 / (this.data.ratio),
          line_bottom_y = canvasHeight - (16 / this.data.ratio),
          line_bottom_h = 16 / (this.data.ratio);
      // 繪製背景圖
      canvas.setFillStyle('white');
      canvas.fillRect(0, 0, canvasWidth, canvasHeight)   
      canvas.drawImage(res[1].path, 0, car_contain_y, car_contain_w, car_contain_h);
      canvas.drawImage(res[2].path, 0, 0, car_contain_w, white_bg_y);
      canvas.drawImage(res[3].path, logo_x, logo_y, logo_w, logo_h);
      canvas.drawImage(res[4].path, g50logo_x, g50logo_y, g50logo_w, g50logo_h);
      canvas.drawImage(res[5].path, g50title_x, g50title_y, g50title_w, g50title_h);
      canvas.drawImage(res[6].path, 0, line_bottom_y, car_contain_w, line_bottom_h);
      canvas.restore();
      // 繪製二維碼
      canvas.drawImage(res[0].path, ercode_x, ercode_y, ercode_canvasWidth, ercode_canvasHeight);
      // 繪製文字
      canvas.setFontSize(15 / this.data.ratio);
      canvas.fillStyle = "#000";
      canvas.fillText("開啟微信掃碼檢視詳情", txt_x, txt1_y);
      canvas.fillText("分享到朋友圈", txt_x, txt2_y);
      canvas.draw();
      setTimeout(function () {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: canvasWidth,
          height: canvasHeight,
          canvasId: 'shareCanvas',
          success: function (res) {
            //console.log(res)
            that.setData({
              postUrl: res.tempFilePath,
            })
            wx.hideLoading()
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }, 500)
    })
  },

  //儲存圖片
  savePic: function () {
    let that = this;
    //console.log("儲存圖片,大畫布", that.data.postUrl)
    wx.saveImageToPhotosAlbum({
      filePath: that.data.postUrl,
      success: function (data) {
        wx.showToast({
          title: '圖片儲存成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
  },

  //關閉
  closeRejectModal: function () {
    this.setData({
      modalDisplay: false
    })
  }
})