1、安装
npm install --save html2canvas
2、导入
import html2canvas from "html2canvas"
3、基本语法
let dom = document.getElementById("id");
html2canvas(dom, {
backgroundColor: "#fff",
}).then((res) => {
let url = res.toDataURL("image/png");
console.log(url)
});
4、可用参数
参数名称 | 类型 | 默认值 | 描述 |
allowTaint | boolean | false | 允许跨域 |
width | number | null | canvas宽度 |
height | number | null | canvas高度 |
background | string | #fff | canvas的背景颜色,如果没有设定默认透明 |
letterRendering | boolean | false | 在设置了字间距的时候有用 |
logging | boolean | false | 在console.log()中输出信息 |
proxy | string | undefined | 代理地址 |
taintTest | boolean | true | 是否在渲染前测试图片 |
timeout | number | 0 | 图片加载延迟,默认延迟为0,单位毫秒 |
useCORS | boolean | false |
5、截屏并下载
运行效果:
源码:
<template>
<div>
<span title="截屏" class="iconfont icon-screenshot" @click="handleClickSreen"></span>
<el-dialog :area="[900,614]" title="截屏" :visible.sync="isShowDialog">
<img :src="canvasUrl" class="screen-img" />
<div slot="footer" class="dialog-footer">
<a download="截屏" :href="canvasUrl">下 载</a>
<el-button @click="isShowDialog = false">取 消</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import html2canvas from "html2canvas"
export default {
data() {
return {
isShowDialog: false,//是否展示截图弹窗
canvasUrl: ""
}
},
methods: {
// 截屏
handleClickSreen() {
let dom = document.getElementById("app");
html2canvas(dom)
.then((res) => {
this.canvasUrl = res.toDataURL("image/png");
if (this.canvasUrl) {
this.isShowDialog = true;
}
});
},
}
}
</script>
<style scoped lang="less">
.dialog-footer a{
display: inline-block;
background-color: #e72528;
width: 96px;
height: 32px;
border: 1px solid #e72528;
color: #fff;
line-height: 30px;
text-align: center;
cursor: pointer;
border-radius: 2px;
text-decoration: none;
transition: all 0.2s;
margin-right: 8px;
&:hover {
background-color: #EC5153;
border-color: #EC5153;
}
}
</style>