最近开发业务中需要对榜单进行图片转化并支持下载,使用html2canvas来实现。不过榜单内容过长,一屏展示不完,而html2canvas也确实有只展示当前这样的问题。
首先进行安装
npm install html2canvas --save
然后在页面中导入html2canvas
import html2canvas from 'html2canvas';
封装了一个方法,用来生成图片,因为页面数据太多又有图片,内容比较多,出现了纵向的滚动条,截图出来的效果只能截取到视图窗口显示的部分,超出窗口部分则无法生成,找了很多方法,使用让页面滚动,多次生成canvas,然后再拼接的方式
<div class="ranking" id="tableBox">
<ul>
<li></li>
</ul>
</div>
<div @click="handlerPreviewImage">生成图片</div>
<script>
methods:{
async captureFullPageManual (id) {
const element = document.getElementById(id);
const height = element.scrollHeight;
const windowHeight = window.innerHeight;
const windowWidth = window.innerWidth;
let y = 0;
const promises = [];
while (y < height) {
window.scrollTo(0, y);
promises.push(html2canvas(element, {
width: windowWidth,
height: windowHeight,
scale: 1,
scrollY: -y,
}));
y += windowHeight;
}
const canvases = await Promise.all(promises);
const images = canvases.map((canvas) => canvas.toDataURL());
const fullCanvas = document.createElement('canvas');
fullCanvas.width = windowWidth;
fullCanvas.height = height;
const ctx = fullCanvas.getContext('2d');
images.forEach((imgData, index) => {
const img = new Image();
img.src = imgData;
img.onload = () => {
ctx.drawImage(img, 0, index * windowHeight);
if (index === images.length - 1) {
const finalImage = fullCanvas.toDataURL();
return finalImage;
}
return false;
};
});
// 返回最终的完整图像
return new Promise((resolve) => {
let loadedCount = 0;
images.forEach((imgData, index) => {
const img = new Image();
img.src = imgData;
img.onload = () => {
ctx.drawImage(img, 0, index * windowHeight);
loadedCount += 1;
if (loadedCount === images.length) {
const finalImage = fullCanvas.toDataURL();
resolve(finalImage);
}
};
});
});
};
handlerPreviewImage(){
this.captureFullPageManual('tableBox')
}
}
</script>
这样的方法虽然可能生成长图,但是后面拼接的图片却是从页面开始处拼接的。
无奈只能再去寻找解决办法,翻看html2canvas的文档,研究与高度相关的属性,最后在设置了如下两个属性后问题终于得到解决!还不用多次拼接那么麻烦!
try {
// 获取需要渲染的元素
const element = document.getElementById('tableBox'); //
// 获取页面的总高度
const totalHeight = element.scrollHeight;
const canvas = await html2canvas(element, {
height: totalHeight,
windowHeight: totalHeight,
scale: 1,
});
// 将canvas 转换为图片并下载
const imgData = canvas.toDataURL('image/png');
...(后续业务代码)
} catch (error) {
console.error(error);
}