uniapp保存canvas生成的图片到本地

1.app端

uni.saveImageToPhotosAlbum({
  filePath: res.tempFilePath,
  success: () => {
    uni.showToast({
      title: that.$t('保存成功'),
      icon: 'success'
    });
  },
  fail: () => {
    uni.showToast({
      title: that.$t('保存失败'),
      icon: 'none'
    });
  }
});

2.H5端

saveH5Canvas(res) {
  try {
    // 在 h5 中,res.tempFilePath 返回的是 base64 类型要处理,通过 a 标签的形式下载
    var arr = res.tempFilePath.split(',');
    var bytes = atob(arr[1]);
    let ab = new ArrayBuffer(bytes.length);
    let ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    var blob = new Blob([ab], {
      type: 'application/octet-stream'
    });
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url;
    a.download = new Date().valueOf() + ".png";
    var e = document.createEvent('MouseEvents');
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
    URL.revokeObjectURL(url);
    this.$util.Tips({title: this.$t('保存成功')})
  } catch (e) {
    this.$util.Tips({title: this.$t('保存失败')})
    //TODO handle the exception
  }


}

3.完整代码

const ctx = uni.createCanvasContext(this.canvasId, this);
// 绘制完成  
ctx.draw(true, function () {
  uni.canvasToTempFilePath({
    canvasId: that.canvasId,
    success: (res) => {
      // #ifdef H5
      that.saveH5Canvas(res)
      // #endif
      console.log(res.tempFilePath, "临时路径");
      // #ifdef APP
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: () => {
          uni.showToast({
            title: that.$t('保存成功'),
            icon: 'success'
          });
        },
        fail: () => {
          uni.showToast({
            title: that.$t('保存失败'),
            icon: 'none'
          });
        }
      });
      // #endif

    },
    fail: (err) => {
      console.log(err, "错误信息");
    }
  });

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值