html2canvas.vue
2.59 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<template>
<div>
<!-- 生成图片后隐藏原始结构 -->
<div v-if="flag" ref="canvasRef" style="width: 200px; height: 200px;">
<img :src="logo_image" alt="">
</div>
<div v-if="imgUrl">
<img :src="imgUrl" alt="" crossOrigin="anonymous" style="width: 300px; height: 300px;">
</div>
<div>
<div @click="createImage">合成图片</div>
<div @click="btn">child</div>
</div>
<router-view />
</div>
</template>
<script setup>
import logo_image from '@images/logo@3x.png'
</script>
<script>
import mixin from 'common/mixin';
import html2canvas from "html2canvas";
export default {
mixins: [mixin.init],
data() {
return {
imgUrl: "",
flag: true
}
},
mounted() {
},
methods: {
createImage() {
this.$nextTick(() => {
// 获取要生成图片的 DOM 元素
let canvasDom = this.$refs.canvasRef;
const options = {
// backgroundColor: '#ffffff',
// canvas: canvas,
useCORS: true,//配置允许跨域
// scale:1,
// windowWidth: document.body.scrollWidth,
// windowHeight: document.body.scrollHeight,
// x: 0,
// y: window.pageYOffset,
// allowTaint: true,
// background: "#ffffff", // 一定要添加背景颜色,否则出来的图片,背景全部都是透明的
dpi: 300 // 处理模糊问题
};
// console.log("获取指定的宽高", width, height, canvas);
html2canvas(canvasDom, options)
.then(canvas => {
try {
// 生成图片地址
this.imgUrl = canvas.toDataURL("image/png");
// console.log("canvas.toDataURL('image/png')", this.imgUrl);
this.flag = false;
} catch (e) {
alert("图片跨域,保存失败");
}
})
.catch(error => {
console.error("绘制失败");
console.error(error);
});
});
},
btn () {
this.$router.push({
path: '/image/children',
query: {
abc: 1
}
})
}
}
}
</script>
<style lang="less" scoped>
.m-html2canvas {
display: flex;
}
.m-canvasRef {
width: 500px;
height: 500px;
/* border: 1px solid red; */
/* box-sizing: border-box; */
box-shadow: 10px 10px 5px #888888;
}
.m-imageList {
width: 500px;
height: calc(500px / 3);
}
img {
width: 100%;
height: 100%;
float: left;
}
.m-showImage {
margin-left: 50px;
background: red;
width: 500px;
height: 500px;
}
.m-btn {
margin-left: 50px;
}
</style>