vue2 截取界面指定区域示例
<template>
<div>
<div ref="captureArea" class="captureArea" style="">这里是需要截屏的区域</div>
<button @click="captureImage">截图</button>
</div>
</template>
<script>
//npm install html2canvas --save
import html2canvas from "html2canvas";
export default {
data() {
return {
capturedImage: "", // 保存截图后的图片链接
};
},
methods: {
//抓取当前页面指定区域的图像。
captureImage() {
console.log(this.$refs.captureArea);
html2canvas(this.$refs.captureArea).then((canvas) => {
this.downloadImage(canvas.toDataURL("image/png"), "captured.png"); //下载图片
this.copyToClipboard(canvas.toDataURL("image/png")); //复制到剪切板
});
},
// 下载图片
downloadImage(imageSrc, imageName) {
const a = document.createElement("a");
a.href = imageSrc;
a.download = imageName || "download.png";
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
},
// 复制到剪切板
async copyToClipboard(imageSrc) {
const blob = await fetch(imageSrc).then((r) => r.blob());
const item = new ClipboardItem({ "image/png": blob });
try {
await navigator.clipboard.write([item]);
console.log("Image copied to clipboard");
} catch (err) {
console.error("Unable to copy image to clipboard", err);
}
},
},
};
</script>
<style>
/* 指定区域的样式 */
.captureArea {
display: flex;
justify-content: center;
color: red;
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 10px;
background-color: #ccc
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
编辑此页 (opens new window)
上次更新: 2024/08/23, 11:12:54