小程式canvan畫布,現兩張圖片合成一張,並儲存到本地

Treasure girl1發表於2020-09-29

微信小程式合成照片 應用canvas把他們繪製到一張圖上儲存到本地相簿然後點選分享

自定義一個元件

components/canvas.js裡

// components/canvas/canvas.js
const app = getApp()
Component({
  /**
   * 元件的屬性列表
   */
  properties: {
    scene: {
      type: String,
      value: ''
    }
  },

  /**
   * 元件的初始資料 
   */
  data: {
    pixelRatio: 2,
    programCode: '',
    count: 0,
    spinning: false,
    loadingFlag: false, // 是否重新載入圖片
    image:''
  },
  // 在元件完全初始化完畢、進入頁面節點樹後
  attached () {
    wx.nextTick(() => {
      this.getFile() // 獲取小程式碼和頭像的臨時檔案
    })
  },

  /**
   * 元件的方法列表
   */
  methods: {
    getFile () {
      // 請求介面 獲取頭像和小程式碼的臨時檔案
      if (!this.data.loadingFlag) {
        this.initData()
      }
    },
    writeCanvas () {
      let that = this
      const ctx = wx.createCanvasContext('myCanvas', that)
      let canvasW = that.data.canvasW
      let canvasH = that.data.canvasH
      let bgImgPath = that.data.image //背景圖片(在這裡換圖片)
      let programCode = that.data.erweima // 小程式碼(在這裡換圖片)
      // 畫大背景 單位是 px 不是 rpx
      ctx.drawImage(bgImgPath, 0, 0, canvasW, canvasH)
      // 儲存上下文
      ctx.save()
      // 恢復畫布
      ctx.restore()
      // 畫小程式碼
      ctx.drawImage(programCode, that.computedPercent(85), that.computedPercent(165), that.computedPercent(117), that.computedPercent(117))
      ctx.draw(true, () => {
        that.setData({
          spinning: false
        })
      })
    },
    // 初始化資料
    initData () {
      let that = this
      // 獲取裝置寬度,計算canvas寬高
      wx.getSystemInfo({
        success: function(res) {
          let canvasW = Math.round(res.screenWidth *0.978)
          let canvasH = canvasW * 1.929
          that.setData({
            pixelRatio: res.pixelRatio, // 圖片畫素比
            canvasW,
            canvasH
          })
          that.writeCanvas() // 暫時在此執行
        }
      })
    },
    // 儲存圖片
    save () {
      let that = this
      wx.canvasToTempFilePath({
        x: 0, // 起點橫座標
        y: 0, // 起點縱座標
        width: that.data.canvasW, // canvas 當前的寬
        height: that.data.canvasH, // canvas 當前的高
        destWidth: that.data.canvasW * that.data.pixelRatio, // canvas 當前的寬 * 裝置畫素比
        destHeight: that.data.canvasH * that.data.pixelRatio, // canvas 當前的高 * 裝置畫素比
        canvasId: 'myCanvas',
        success: function (res) {
          console.log(res)
          //調取小程式當中獲取圖片
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              wx.showToast({
                title: '圖片儲存成功!',
                icon: 'none'
              })
            },
            fail: function (res) {
              console.log(res)
              if (res.errMsg === "saveImageToPhotosAlbum:fail auth deny" || res.errMsg === "saveImageToPhotosAlbum:fail:auth denied") {
                that.doAuth()
              }
            }
          })
        },
        fail: function (res) {
          console.log(res)
        }
      }, this)
    },
    // 獲取授權
    doAuth () {
      wx.showModal({
        title: '獲取授權',
        content: '您是否同意重新授權儲存圖片',
        cancelText: '不同意',
        confirmText: '同意',
        confirmColor: '#21c0ae',
        success: function(res) {
          if (res.confirm) { // 點選確認
            wx.openSetting({
              success(settingdata) {
                if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                  console.log("獲取許可權成功,再次點選圖片儲存到相簿")
                } else {
                  console.log("獲取許可權失敗")
                }
              },
              fail: function (res) {
                console.log(res)
              }
            })
          }
        }
      })
    },
    /**
     * 計算比例
     * @param {String} value 畫素(二倍圖量出來的要除2)
     */
    computedPercent (value) {
      let currentWidth = this.data.canvasW
      let oldWidth = 288
      return Math.floor(value * currentWidth / oldWidth)
    }
  },
  created: function () {
    let that = this
    let image = wx.getStorageSync('images')
    var erweima =wx.getStorageSync('erweima')
    that.setData({
      image:image,
      erweima:erweima
    })
  },
})

components/canvas.wxml裡

<!--components/canvas/canvas.wxml-->
<view class="generate-pic-box">
  <view class="mask" wx:if="{{spinning}}">
    <view class="mask-cont">
      <view class="loading"></view>
    </view>
  </view>
  <block hidden="{{!spinning}}">
    <canvas class="canvas" style="{{'width: ' + (canvasW) + 'px; height: ' + (canvasH) + 'px;'}}" canvas-id="myCanvas"
      hidden="{{canvasHidden}}"></canvas>
    <!-- <view class="save-text">儲存圖片,分享至朋友圈</view> -->
  </block>
  <!-- <view class="save-btn-box"> -->

  <cover-view  class="btuns">
    <button open-type="share" class="button">分享</button>
  </cover-view>
  <cover-view class="save-btn" bindtap="save">儲存圖片</cover-view>
  <!-- </view> -->
</view>

components/canvas.wxss裡

.generate-pic-box {
  width: 100%;
  position: relative;
}
.generate-pic-box .mask {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1001;
  background-color: rgba(255, 255, 255, 0.5);
}
.generate-pic-box .mask .mask-cont {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.generate-pic-box .mask .mask-cont .loading {
  width: 36rpx;
  height: 36rpx;
  margin-right: 20rpx;
}
.generate-pic-box .mask .mask-cont .loading-text {
  color: #fff;
}
.generate-pic-box .canvas {
  margin: 0 auto;
}
.generate-pic-box .generate-pic-btm {
  padding-top: 24rpx;
  padding-bottom: 30rpx;
  background-color: #fff;
}
.generate-pic-box .save-text {
  width: 100%;
  margin-bottom: 21rpx;
  font-size: 26rpx;
  line-height: 1.5;
  color: #999;
  text-align: center;
}
 .save-btn-box {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.save-btn {
  width: 84%;
  height: 64rpx;
  line-height: 64rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  text-align: center;
  color: #fff;
  margin-left: 60rpx;
  position: absolute;
  z-index: 1000;
  bottom: 80rpx;
  background: #076BFF ;
}
.btuns {
  width: 84%;
  color: #fff;
  font-size: 29rpx;
  position: absolute;
  bottom: 171rpx;
  border-radius: 8rpx;
  background: #076BFF ;
  margin-left: 60rpx;
}
.button {
  /* width: 84%; */
 
  color: #fff;
  font-size: 29rpx;
  border-radius: 8rpx;
  background: #076BFF ;
}

把元件引入json裡

 "usingComponents": {
    "canvas": "../../components/canvas/canvas"
  },

直接在wxml裡呼叫就行了

  <view class="component-display-box">
		<generate-pic></generate-pic>
  </view>

合成照片必須是本地圖片 如果用網路圖片 要先下載到本地wx.downloadFile官網上也都有詳細說明的。重要的一點 下載完圖片真機除錯什麼的照片都可以顯示 如果上傳為測試版的話 圖片沒有顯示 那就說明下載的路徑的問題了可以在url 里加replace("http:","https:"),一定要加在圖片地址後面

如果有更好的 歡迎一起討論

相關文章