hookehuyr

✨ feat: 测试dom转图片功能

This diff could not be displayed because it is too large.
......@@ -9,6 +9,7 @@
"serve": "vite preview"
},
"dependencies": {
"html2canvas": "^1.4.1",
"jquery": "^3.6.0",
"lodash": "^4.17.21",
"moment": "^2.29.1",
......
......@@ -6,4 +6,11 @@ export default [{
title: ''
},
children: []
}, {
path: '/image',
name: 'html转图片',
component: () => import('./views/html2canvas.vue'),
meta: {
title: ''
}
}];
\ No newline at end of file
......
<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>
</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(err => {
console.log("绘制失败");
});
});
}
}
}
</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>
\ No newline at end of file
......@@ -10,16 +10,13 @@
import mixin from 'common/mixin'
import { mainStore } from '@/store'
import { storeToRefs } from 'pinia'
export default {
mixins: [mixin.init],
data () {
return {
}
},
mounted () {
},
methods: {
......
This diff is collapsed. Click to expand it.