vue3实现导出png

28 篇文章 3 订阅

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、效果

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值