当前位置:   article > 正文

微信小程序-生成canvas图片并保存到手机相册_小程序canvas导出图片

小程序canvas导出图片

wxml页面

<button class="rightbtn bottomBtnCss"  catch:tap="canvasImg">
        <image src='{{imgUrl}}/images/mine/jspj-icon.png' class="restNumImg"></image>
        <text class="btnText">生成图片</text>
      </button>
  • 1
  • 2
  • 3
  • 4
<!-- 生成图片弹框 -->
<view class="wx-dialog_wrapper "  wx:if="{{isShowCanvas}}" >
  <view class="wx-dialog wx-dialogwidth80">
    <view class="wx-dialog_body">
      <view class="canvasWrap"><canvas type="2d" id='posterCanvas' style="width: 100%;height: 1000rpx;"></canvas></view>
      <button class="rightbtn bottomBtnCss"  catch:tap="saveImg">
        <image src='{{imgUrl}}/images/mine/jspj-icon.png' class="restNumImg"></image>
        <text class="btnText">保存图片</text>
      </button>
    </view>
  </view>
</view>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

wxss页面

.wx-dialogwidth80{
  width:80%;
}
#posterCanvas {
  margin: 0 auto;
}
.canvasWrap {
margin: 10px auto;
text-align: center;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

js代码

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: app.globalData.imgUrl,//线上图片路径
    totalCnt: '',
    isSaveCanvas: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let totalCnt = wx.getStorageSync('totalCnt')
    this.setData({
      totalCnt: totalCnt || '0.00'
    })
  },
  // 重新计算
  restClick() {
    wx.navigateTo({
      url: '../../index'
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },
  // 关闭
  showVipDialogClose() {
    this.setData({
      isShowCanvas: false
    })
  },
  canvasImg() {
    this.setData({
      isShowCanvas: true
    })
    // wx.showLoading({
    //   title: '海报生成中...',
    // })
    let _this = this
    //选取画板
    const query = wx.createSelectorQuery()
    query.select('#posterCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec(async (res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const dpr = wx.getSystemInfoSync().pixelRatio //手机分辨率 为了使保存到相册的图片清晰
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        console.log('dpr', dpr);
        ctx.clearRect(0, 0, 320, 410); //清空画板
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, 320, 410);
        // 1.背景图
        const image = canvas.createImage();
        image.src = this.data.imgUrl + "/images/carbonEmissionImages/排放总量背景.png";;
        let bgImg = await new Promise((resolve, reject) => {
          image.onload = () => {
            resolve(image)
          }
          image.onerror = (e) => {
            reject(e)
          }
        });
        ctx.drawImage(bgImg, 0, 0, canvas.width, canvas.height);
        // 2.头部文字 在背景图上作画
        // 设置文字样式
        ctx.font = "700 36px sans-serif";
        ctx.fillStyle = "#fff";
        ctx.textAlign = "center" //居中是以文字设定的x轴( canvas.width/2)为中心点
        // 添加文字
        ctx.fillText("我在ESGPRO上测了企业碳排放总量", canvas.width / 2, 200);
        // 3.画中心圆图
        const image1 = canvas.createImage();
        image1.src = this.data.imgUrl + "/images/carbonEmissionImages/tco2背景.png";;
        let bgImgPo = await new Promise((resolve, reject) => {
          image1.onload = () => {
            resolve(image1)
          }
          image1.onerror = (e) => {
            reject(e)
          }
        });
        ctx.drawImage(bgImgPo, 0.5 * (canvas.width - 400), 0.5 * (canvas.height - 800), 400, 400);
        // 4.圆圈内文字 在背景图上作画
        // // 设置文字样式
        ctx.font = "700 36px sans-serif";
        ctx.fillStyle = '#00bf5b'; //文字颜色:默认黑色
        ctx.textAlign = "center"
        ctx.fillText(_this.data.totalCnt, canvas.width / 2, 0.5 * (canvas.height - 400)) //绘制文本
        // 设置文字样式
        ctx.font = "28px sans-serif";
        ctx.fillStyle = "#bdbdbd";
        ctx.textAlign = "center" //居中是以文字设定的x轴( canvas.width/2)为中心点
        // 添加文字
        ctx.fillText('tCO2', canvas.width / 2, 0.5 * (canvas.height - 300));

        // 5.小程序二维码
        let image2 = canvas.createImage();
        // image2.src = this.data.imgUrl + '/images/carbonEmissionImages/COimg.jpg'; // 引入本地图片
        image2.src = '../../images/COimg.jpg'; // 引入本地图片
        image2.onload = function () {
          ctx.drawImage(image2, 0.5 * (canvas.width - 300), 0.5 * (canvas.height + 400), 300, 300);
          // 6.添加文字
          // 设置文字样式
          ctx.font = "24px sans-serif";
          ctx.fillStyle = "#999999";
          ctx.textAlign = "center" //居中是以文字设定的x轴( canvas.width/2)为中心点
          // 添加文字
          ctx.fillText('微信扫码或搜索ESGPRO', canvas.width / 2, 0.5 * (canvas.height + 1100));
          ctx.font = "24px sans-serif";
          ctx.fillStyle = "#999999";
          ctx.textAlign = "center" //居中是以文字设定的x轴( canvas.width/2)为中心点
          // 添加文字
          ctx.fillText('即可免费使用碳排放计算器', canvas.width / 2, 0.5 * (canvas.height + 1200));
        }
      })

  },
  async saveImg() {
    let _this = this;
    const query = wx.createSelectorQuery();
    const canvasObj = await new Promise((resolve, reject) => {
      query.select('#posterCanvas')
        .fields({
          node: true,
          size: true
        })
        .exec(async (res) => {
          resolve(res[0].node);
        })
    });
    wx.canvasToTempFilePath({
      canvas: canvasObj, //现在的写法
      success: (res) => {
        console.log(res);
        _this.setData({
          isShowCanvas: false
        });
        //保存图片
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.hideToast();
            wx.showModal({
              title: '图片保存成功',
              content: '图片成功保存到相册了',
              showCancel: false,
              confirmText: '好哒',
              confirmColor: '#5096cd',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                }
              }
            })
          },
          fail(err) {
            wx.hideToast()
            if (
              err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" ||
              err.errMsg === "saveImageToPhotosAlbum:fail auth deny" ||
              err.errMsg === "saveImageToPhotosAlbum:fail authorize no response"
            ) {
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: res => {
                  wx.openSetting({
                    success(res) {
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败,将无法保存到相册哦~',
                          showCancel: false,
                        })
                      }
                    },
                    fail(err) {
                      console.log("fail", err)
                    },
                    complete(res) {
                      console.log("finish", res)
                    }
                  })
                }
              })
            } else if (err.errMsg === "saveImageToPhotosAlbum:fail cancel") {
              wx.showModal({
                title: '提示',
                content: '取消了保存图片,再次点击下载即可保存',
                showCancel: false,
              })
            } else {
              wx.showModal({
                title: '提示',
                content: err.errMsg,
                showCancel: false,
              })
            }
          }
        })
      },
      fail(err) {
        wx.showToast({
          title: '保存失败,稍后再试',
          duration: 2000,
          icon: 'none'
        });
      }
    }, this)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/43587
推荐阅读
相关标签
  

闽ICP备14008679号