微信小程序-生成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>
<!-- 生成图片弹框 -->
<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>

wxss页面

.wx-dialogwidth80{
  width:80%;
}
#posterCanvas {
  margin: 0 auto;
}
.canvasWrap {
margin: 10px auto;
text-align: center;
}

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() {

  },

})
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值