h5采用html2canvas实现html转canvas保存图片
安装 npm install --save html2canvas 或 yarn add html2canvas
引入import html2canvas from ‘html2canvas’;
ts
function getCanvas() {
uni.showModal({
title: '提示',
content: '您要保存图片到相册吗?',
success(res) {
if (res.cancel) {
return;
}
// '#businessReport‘ 当前要保存为图片的代码块的id
const id = document.querySelector('#businessReport') as HTMLElement; // ts标注类型
html2canvas(id, {
useCORS: true,
allowTaint: true,
windowHeight: id.scrollHeight, // 如果图片过长,可能会出现图片保存部分空白,scrollHeight是包含滚动条的高度
// scale和dpi可以调节图片清晰度, 选项{dpi:96}等价于{scale:1},并且任何选项的更大值都将提高分辨率。如果存在两个选项,scale则忽略使用dpi的比例。
scale: 1,
}).then((canvas: any) => {
// 简单的h5直接转blob下载就可以了
canvas.toBlob((blob) => {
console.log(blob);
const imgUrl = URL.createObjectURL(blob);
const aImg = document.createElement('a');
aImg.href = imgUrl;
// 使用该行,点击生成的图片没有.png后缀
// aImg.download = this.imgUrl
// 修改后点击生成的图片有.png后缀,可以预览
aImg.download = Date.now() + '.png';
document.body.appendChild(aImg);
aImg.click();
document.body.removeChild(aImg);
}, 'image/png');
})
}
})
}