网页截图、下载、导出图片功能
🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓 🍓
一、下载插件命令:
npm install --save html2canvas
二、页面引用:
<template>
<div class="demo-1" ref="canvasImg">
<el-button type="primary" @click="handleSave()">主要按钮</el-button>
<div class="box"></div>
<p>测试html2canvas截长图功能</p>
</div>
</template>
<script>
import html2canvas from "html2canvas";
export default {
props: {},
data() {
return {}
},
methods:{
handleSave(){
let that = this;
let imgHeight = that.$refs.canvasImg.offsetHeight; // 获取DOM高度
let imgWidth = that.$refs.canvasImg.offsetWidth; // 获取DOM宽度
// 截取海报
html2canvas(that.$refs.canvasImg, {
useCORS: true, //允许跨域
backgroundColor: '#ececec', //画布背景色,设置null为透明
width: imgWidth, //画布宽
height: imgHeight, //画布高
scale: 2, // 处理模糊问题
dpi: 300, // 处理模糊问题
}).then((canvas) => {
// 返回一个 canvas 对象,在dom中渲染 canvas 对象
// 转化成 dataurL
let url = canvas.toDataURL("image/png");
that.imgUrl = url;
//调用下载方法
let a = document.createElement("a"); //创建一个a标签
let event = new MouseEvent("click"); // 创建一个单击事件
a.download = "海报"; // 设置图片名称
a.href = that.imgUrl; //指定下载文件名称
a.dispatchEvent(event); // 触发a的单击事件
// 这里可以获得截取到的base64格式的图片-url,可进行后续操作,比如传入接口等
});
}
}
}
</script>
<style scoped lang="scss">
.demo-1{
background: green;
}
.box{
height:1000px;
width:100%;
}
</style>
三、寄语:
人是自然的孩子,亲近自然是人的天性。青山绿水中藏着返璞归真的灵气,当你走出去,每一步都会是欢喜。