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, "错误信息");
}
});
})