这种方法可以用来捕获页面上的任意元素并将其转换为图片格式进行下载,适合于生成包含特定内容的图片(如海报、证书等)。
安装插件 npm install html2canvas
<template>
<div>
<div ref="contentRef" style="padding: 20px; border: 1px solid #ccc;">
<h1>Hello Vue 3</h1>
<p>这是一段要下载为图片的内容。</p>
<!-- 如果包含跨域图片 -->
<img src="https://example.com/cross-origin-image.jpg" alt="Cross Origin Image">
</div>
<button @click="downloadAsImage">下载为图片</button>
</div>
</template>
<script setup>
import { ref, nextTick } from 'vue';
import html2canvas from 'html2canvas';
const contentRef = ref(null);
const downloadAsImage = async () => {
await nextTick(); // 确保 DOM 更新完成
const element = contentRef.value;
if (!element) {
console.error('元素未找到');
return;
}
try {
const canvas = await html2canvas(element, {
useCORS: true // 启用跨域支持
});
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = 'content.png';
link.click();
} catch (error) {
console.error('截图失败:', error);
}
};
</script>