1-在要生成截图的页面中,给要生要成截图的部分定义id名
<view id="poster">
2-按钮点击保存图片事件
<button type="primary" class='myButton' @click="renderScript.exportPhoto">保存图片</button>
3-在第一个script中
<script>
import {
base64ToPath
} from '@/shopro/poster/QS-SharePoster/image-tools.js';
export default {
data() {
return {}
},
methods: {
receiveRenderData(data) {
let that = this;
uni.hideLoading();
base64ToPath(data, '.jpeg').then(function(imgPath) {
// #ifdef H5
//H5生效
uni.downloadFile({
url: imgPath,
success: (res) => {
var link = document.createElement('a');
link.href = imgPath;
link.download = '小票信息.png';
// link.download = imgPath.replace(/(.*\/)*([^.]+.*)/ig,"$2").split("?")[0];
link.click();
}
})
// #endif
// #ifndef H5
//除了H5其他身边生效
uni.saveImageToPhotosAlbum({
filePath: imgPath,
success: function() {
uni.showModal({
content: "保存成功,请到相册查看",
showCancel: false,
});
},
fail: err => {
console.log('保存失败' + `:`, err);
that.$u.toast('保存失败');
}
});
// #endif
})
},
openLoading() {
uni.showLoading({
title: '保存相册中...'
})
},
}
}
</script>
3-第二个script
使用renderjs
<script module="renderScript" lang="renderjs">
import html2canvas from 'html2canvas';
import {
base64ToPath
} from '@/shopro/poster/QS-SharePoster/image-tools.js';
export default {
methods: {
exportPhoto(e, ownerVm) {
ownerVm.callMethod('openLoading')
var dom = document.querySelector('#poster'); // 获取dom元素
html2canvas(dom, {
width: dom.clientWidth, //dom 原始宽度
height: dom.clientHeight,
scrollY: 0,
scrollX: 0,
useCORS: true, //支持跨域,但好像没什么用
}).then((canvas) => {
// 将生产的canvas转为base64
var base64 = canvas.toDataURL('image/png')
// 将数据回调给第一个script
ownerVm.callMethod('receiveRenderData', base64)
}).catch((e) => {
console.log(e);
});
}
}
}
</script>