1. 安装 html2canvas
首先,你需要安装 html2canvas
:
npm install html2canvas
2. 创建 Vue 组件
接下来,创建一个 Vue 组件,并在其中使用 html2canvas
来导出页面为图片。
<template>
<div ref="contentRef">
<!-- 你的超长页面内容 -->
</div>
<button @click="exportToImage">导出为图片</button>
</template>
<script setup>
import { ref } from 'vue';
import html2canvas from 'html2canvas';
const contentRef = ref(null);
const exportToImage = async () => {
try {
const element = contentRef.value;
if (!element) return;
// 配置选项(关键参数)
const options = {
scale: 2, // 提升清晰度
useCORS: true, // 允许跨域图片
allowTaint: true, // 处理tainted canvas问题
scrollY: -window.scrollY, // 消除滚动偏移
windowHeight: document.documentElement.scrollHeight, // 完整页面高度
};
// 生成Canvas
const canvas = await html2canvas(element, options);
// 转换为图片并下载
const imgData = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = 'page-screenshot.png';
link.href = imgData;
link.click();
} catch (error) {
console.error('导出失败:', error);
}
};
</script>
这样就可以实现页面直接导出为图片的功能