vue项目中将html的DOM元素截图生成图片函数封装
此方法在vue2和vue3中都适用。
第一步:下载安装html2canvas
npm install --save html2canvas
第二步:在js中封装
import html2canvas from "html2canvas"
/* 利用html2canvas将DOM生成图片并下载
* 参数:
* refDom:ref
* imageName:生成并下载的图片名称,默认年月日时分秒
* scale:图片缩放比例,默认不缩放
* imageType下载图片格式,默认png格式weuh
* backgroundColor:图片背景色,默认白色 注:透明色传nul
*/
export function domToImage(refDom, imageName = false, scale = 1, imageType = "image/png", backgroundColor = '#fff') {
if (imageName === false) {
let nowDate = new Date()
imageName = '' + nowDate.getFullYear() + (nowDate.getMonth() + 1) + nowDate.getDate() + nowDate.getHours() + nowDate.getMinutes() + nowDate.getSeconds()
}
const canvas = document.createElement("canvas")
const width = parseInt(window.getComputedStyle(refDom).width)
const height = parseInt(window.getComputedStyle(refDom).height)
canvas.width = width * scale
canvas.height = height * scale
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
const ctx = canvas.getContext("2d");
ctx.scale(scale, scale);
const options = {
backgroundColor,
canvas,
useCORS: true
}
html2canvas(refDom, options).then((canvas) => {
let a = document.createElement('a')
a.href = canvas.toDataURL(imageType)
a.download = imageName
a.click()
})
}
注:此函数可以直接复制过去使用,无需修改,也可以根据需求修改。
第三步:调用函数
html中触发即可
<div ref="trendsRef" class="container">
<el-button @click="domToImage(trendsRef)">下载</el-button>
<div>图片内容为container容器内部内容,包含container容器样式。</div>
</div>
<!-- 下载按钮位置没有限制,可以在下载区域内部,也可以在下载区内外部,主要作用就是触发函数执行。 -->
<el-button @click="domToImage(trendsRef)">下载</el-button>
js声明ref的DOM结构
// ref在state中声明:
const state = reactive({
trendsRef:null
});
// ref也可以用const声明:
import { reactive, toRefs, ref } from "vue";
const trendsRef = ref(null)