在项目安装库 html2canvas
npm i html2canvas
在页面局部加载?html2canvas 库,调用方法生成
<template>
<div class="page-box">
<div class="text-box">文本转图片</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas'
export default {
data() {
return {}
},
mounted() {
this.$nextTick(async () => {
const element = document.querySelector('.text-box')
const canvas_box = await html2canvas(element) // 生成canvas
const img_url = canvas_box.toDataURL('image/png') // 转图片地址base64
const a_tag = document.createElement('a')
a_tag.href = img_url
a_tag.download = 'test.png'
a_tag.click()
})
},
methods: {}
}
</script>
<style lang="less" scoped></style>