1.安装插件 html2canavs插件:
npm install html2canvas
cnpm i html2canvas --save
2.组件中进行引入下载的插件:
import html2canvas from "html2canvas";
3.该组件中使用:
<template>
<div>
<div ref="poster" class="posterImg">
<h3>公告</h3>
<p>
如果同学们的这个项目写的比较快,也能接收额外实战知识,增加难度
</p>
<img src="https://img2.baidu.com/it/u=2683586264,3988923268&fm=253&fmt=auto&app=138&f=JPEG?w=452&h=457" />
</div>
<img :src="posterimg"/>
<button type="button" class="" @click="download">下载</button>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import html2canvas from "html2canvas";
const posterimg = ref();
// 绑定内容生成图片
const poster =ref();
const download= ()=> {
// 通过ref获取元素的自身宽度和高度
// poster.value.offsetWidth poster.value.offsetHeight
// 海报图默认是 2倍尺寸
html2canvas(poster.value,{
backgroundColor:'#f5f5f5',//海报的背景颜色
useCORS:true, // 允许跨域
width:poster.value.offsetWidth, //生成海报的w 默认是px
height:poster.value.offsetHeight, //生成海报的h 默认是px
}).then(res=>{
// res其实就是我们所讲的res 的意思 返回报文的意思
let baseImg = res.toDataURL("image/png");
posterimg.value =baseImg;
let save = document.createElement('a');
// <a href=''></a>
save.href = baseImg;
// 下载的名字
save.download = 'yz'
// 直接回调a的点击事件
save.click()
})
}
</script>