1、安装依赖
npm install --save html2canvas
2、使用
<template>
<el-card class="mb15">
<template #header>
<span>vue3实现导出png</span>
</template>
<div ref="badge" class="badge">
<el-calendar v-model="value" />
</div>
<div style="margin: 20px 0">
<el-button type="primary" size="default" @click="exportPNG">导出png</el-button>
</div>
</el-card>
</template>
<script setup lang="ts" name="demoView">
import { ref } from 'vue';
import html2canvas from 'html2canvas';
const value = ref(new Date());
const badge = ref();
const exportPNG = () => {
html2canvas(badge.value).then((canvas) => {
// const contentWidth = canvas.width;
// const contentHeight = canvas.height;
// 添加水印
/* const ctx = canvas.getContext('2d');
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.rotate((25 * Math.PI) / 180);
ctx.font = '20px Microsoft Yahei';
ctx.fillStyle = 'rgba(184, 184, 184, 0.8)';
for (let i = contentWidth * -1; i < contentWidth; i += 240) {
for (let j = contentHeight * -1; j < contentHeight; j += 100) {
ctx.fillText('磊哥', i, j);
}
} */
const imgUrl = canvas.toDataURL('image/png');
const a = document.createElement('a');
a.style.display = 'none';
a.href = imgUrl;
a.setAttribute('download', '文件名');
if (typeof a.download === 'undefined') {
a.setAttribute('target', '_blank');
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(imgUrl);
});
};
</script>
<style lang="scss" scoped></style>
3、效果