Vue使用html2canvas方法
1.安装
npm install --save html2canvas
2.在需要使用的页面中引用
import html2canvas from 'html2canvas';
3.调用使用
this.$nextTick(() => {
html2canvas(this.$refs.vueDomSaveToImage).then((res) => {
let imgUrl = res.toDataURL('image/jpg');
const save_link = document.createElementNS(
'http://www.w3.org/1999/xhtml',
'a'
);
save_link.href = imgUrl;
save_link.download = this.fileName + '.jpg'; //保存文件名格式为 ***-点名册、会议纪要、等文件名
const event = document.createEvent('MouseEvents');
event.initMouseEvent(
'click',
true,
false,
window,
0,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null
);
//将图片以blob方式下载
async function downloadImage(imgUrl, name) {
try {
const response = await fetch(imgUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = name + '.jpg';
link.click();
this.$notify({
title: this.fileName,
message: '[' + this.fileName + ']' + '保存成功!',
position: 'bottom-right',
type: 'success',
duration: 0,
});
} catch (error) {
console.error('Error downloading image:', error);
}
}
downloadImage(save_link, this.fileName).then(() => {
console.log('finfish');
this.$notify({
title: this.fileName,
message: '[' + this.fileName + ']' + '保存成功!',
position: 'bottom-right',
type: 'success',
});
});
});
});
遇到的问题及解决方法
1.图片导出后变形/比例改变了
图片可能使用了不支持的css属性,比如:object-fit:cover
解决方法:
更换其他css属性以达到需求,比如使用flex以使图片比例不改变居中
.fu{
width: 1240px;
height: 720px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
}
.img {
width: 100%;
}