前端在 Vue 3 中,如果你需要将一个 div 元素的内容转换成图片,可以使用一个高效且流行的库—— html2canvas。这个库能够帮助你将 DOM 元素渲染为 Canvas,并进一步将 Canvas 转换为图片,非常适合在 Vue 项目中使用。
在线演示地址: DOM元素生成截图
npm install html2canvas
<template>
<div>
<div ref="content">
<slot></slot>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
import html2canvas from 'html2canvas';
const content = ref(null);
//捕获截图
const capture = () => {
if (content.value) {
html2canvas(content.value).then((canvas) => {
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = '图片下载.png';
link.click();
});
}
};
//暴露给父组件调用
defineExpose({capture})
</script>
<style scoped>
</style>
<template>
<div>
<ImageCapture ref="ImageCaptureRef">
<h1>Hello, Vue 3!</h1>
<p>这个内容将被转换为一张图片。</p>
</ImageCapture>
<button @click="capture">Capture</button>
</div>
</template>
<script lang="ts" setup>
//引入ImageCapture组件
import ImageCapture from '../components/ImageCapture.vue'
import {ref} from "vue";
const ImageCaptureRef=ref(null)
//捕获图片
const capture=()=>{
ImageCaptureRef.value.capture()
}
</script>
<style scoped>
</style>
如截图出现文字偏移等问题,可尝试更换版本至html2canvas@^1.0.0-alpha.12
:
npm install html2canvas@^1.0.0-alpha.12
# 或者使用yarn
yarn add html2canvas@^1.0.0-alpha.12
如出现以下错误,请切换node版本18.10.0或其他符合的版本。
npm WARN EBADENGINE required: { npm WARN EBADENGINE node: '^14.17.0 || ^16.13.0 || >=18.0.0', npm WARN EBADENGINE npm: '>=6.14.13', npm WARN EBADENGINE pnpm: '>= 7.0.0' npm WARN EBADENGINE },