文章目录
一、前言
在实际业务中,经常会有用户截图保存页面内容的需求,比如:
- 表单填写后的结果截图
- 页面中某个模块的操作记录截图
- 可视化大屏、报表区域导出为图片
而我们可以通过 html2canvas 实现将 DOM 节点截图为图片。本篇文章将基于 Vue 3 + html2canvas 封装一个「可指定区域截图」的组件,支持:
- ✅ 任意 DOM 区域截图
- 🎯 鼠标框选截图区域
- 🖼️ 图片预览与下载
- 🧩 可插入业务模块作为截图内容
二、技术栈与原理简析
- Vue 3 +
<script setup>:组合式 API 更方便封装功能 - html2canvas:将 HTML 节点渲染为 Canvas,再导出为图片
- DOM 操作 + 鼠标事件监听:实现可视化选区
原理核心就是:将目标 DOM 渲染为 canvas,然后将 canvas 导出为 base64 或 Blob 图片。
三、项目准备
3.1 安装依赖
npm install html2canvas
3.2 页面基础布局
我们需要一个区域放置截图目标 + 控制按钮:
<template>
<div class="screenshot-wrapper">
<div class="toolbar">
<button @click="captureFull">📷 截图整个区域</button>
<button @click="toggleCropMode">✂️ 框选截图</button>
</div>
<!-- 可截图区域 -->
<div class="capture-target" ref="captureRef">
<slot />
</div>
<!-- 框选截图遮罩 -->
<div v-if="cropMode" class="crop-mask" @mousedown="startCrop" />
</div>
</template>
四、截图功能实现
4.1 整个区域截图
import html2canvas from 'html2canvas';
const captureRef = ref(null);
function captureFull() {
html2canvas(captureRef.value).then(canvas => {
const img = canvas.toDataURL('image/png');
downloadImage(img);
});
}
function downloadImage(dataUrl) {
const a = document.createElement('a');
a.href = dataUrl;
a.download = 'screenshot.png';
a.click();
}
五、框选截图功能
5.1 实现裁剪区域选择
const cropMode = ref(false);
const cropBox


1万+

被折叠的 条评论
为什么被折叠?



