安装插件
npm install html2canvas --save
插件使用
<template>
<div style="padding: 10px;">
<div ref="imageTofile" class="box">发生什么事了</div>
<button @click="toImage" style="margin: 10px;">截图</button>
<div>
<img :src="htmlUrl" style="height: 288px; width: auto" />
</div>
</div>
</template>
<script>
import html2canvas from "html2canvas";
export default {
data() {
return {
htmlUrl: "",
};
},
methods: {
toImage() {
// 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
html2canvas(this.$refs.imageTofile, {
useCORS: true, // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
}).then((canvas) => {
let url = canvas.toDataURL("image/png");
this.htmlUrl = url;
// 把生成的base64位图片上传到服务器,生成在线图片地址
console.log("base64 => ", this.htmlUrl);
});
},
},
};
</script>
<style scoped>
.box {
width: 512px;
height: 288px;
background-color: yellow;
}
</style>
效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/d6cec9b6499e4cf887aee815359f8f45.png)