业务逻辑:
在html页面显示表格,使用visibility: inherit; 隐藏该表格.点击按钮的时候使用html2canvas把需要转换成图片的dom元素转换成canvas对象,通过onclone回调方法将在canvas对象中找到该表格元素进行显示,返回的canvas图片对象可以通过drawImage()方法添加在canvas画布中.
<!-- 显示canvas页面内容 -->
<template>
<div>
<div class="canvas-wrap">
<canvas id="support-canvas" width="1284" height="600">
不支持canvas
</canvas>
</div>
<el-button type="info" @click="setviewTable">信息按钮</el-button>
<el-table
:data="aSupportTable"
ref="support-table"
id="support-table"
:style="{width:'500px',height:'73px'}"
>
<el-table-column
prop="model"
:label="$t('ledModel')"
width="130">
</el-table-column>
<el-table-column
prop="supportType"
:label="$t('supportType')"
width="115">
</el-table-column>
</el-table>
</div>
</template>
<script>
import html2canvas from 'html2canvas';
export default {
data () {
return {
aSupportTable: [
{
model: '2018/01/02',
supportType: '1111',
address: 'aaaaaaa'
},
{
model: '2018/01/04',
supportType: '22222',
address: 'wwwwwwwwwwww'
}
]
}
},
components:{
},
computed:{
},
watch: {},
methods:{
/**
scale:用于渲染的比例。默认为浏览器设备像素比。
onclone:回调方法当文档被克隆进行渲染时调用的回调函数,可用于修改将要渲染的内容,而不会影响原始源文档。
**/
async viewTable(){
const targetDom = document.querySelector('#support-table');
let tableCanvas = '';
try {
tableCanvas = await html2canvas(targetDom, {
scale: 1,
onclone (doc) {
let e = doc.querySelector('#support-table');
e.style.visibility = 'visible';
}
});
} catch (error) {
console.log(error, 'errror');
}
let canvas = document.getElementById('support-canvas');
let ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (tableCanvas && tableCanvas.width) {
ctx.drawImage(tableCanvas, 0, 0);
}
},
setviewTable(){
this.$nextTick(() => { //等待dom生成之后再获取dom对象
this.viewTable();
});
}
},
created() { },
mounted() {
}
}
</script>
<style lang='less' scoped>
#support-table{
text-align: left;
position: absolute;
left: 0;
visibility: hidden;
/deep/ .el-table__body {
visibility: inherit;
.cell {
padding-left: 4px;
padding-right: 4px;
}
}
/deep/ .el-table__footer {
visibility: inherit;
}
/deep/ .el-table__header {
visibility: inherit;
.cell {
padding-left: 4px;
padding-right: 4px;
}
}
}
.canvas-wrap{
border:1px solid red;
}
</style>
网友评论