小程序canvan画布,现两张图片合成一张,并保存到本地

微信小程序合成照片 应用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:"),一定要加在图片地址后面

如果有更好的 欢迎一起讨论

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页