vue3 使用html2canvas
vue3 使用html2canvas 生成图片并 下载
·
1.安装
npm install html2canvas
2.引入
import html2canvas from 'html2canvas'
3.封装
const autoPicture = async (el, options) => {
let { scale = 1, allowTaint = false, useCORS = true, width = '375', height = '649', backgroundColor = null } = options
const id = document.getElementById(el)
const canvas = await html2canvas(id, {
scale, //缩放比例,默认为1
allowTaint, //是否允许跨域图像污染画布
useCORS, //是否尝试使用CORS从服务器加载图像
width, //画布的宽度
height, //画布的高度
backgroundColor //画布的背景色,默认为透明
})
return canvas.toDataURL('image/png')
}
export { autoPicture }
4.使用
<template>
<div class="swiper">
<div class="capture" :id="'capture' + index" v-for="(i, index) in 3" :key="i">
<img
class="bg"
src="https://img2.baidu.com/it/u=1168755093,1706419808&fm=253&fmt=auto&app=138&f=JPEG?w=754&h=500"
alt=""
/>
<div>
<span style="color: #f00; letter-spacing: 20px">这是文字文字{{ index }}</span>
<span data-html2canvas-ignore="true">不写入canvas</span>
</div>
<div @click="shareImg(index)">点击分享</div>
<img :src="currentImg" v-if="show" alt="" />
</div>
</div>
</template>
<script setup>
import { autoPicture } from '@/utils/autoPicture'
import { ref } from 'vue'
const show = ref(false)
const currentImg = ref('')
const shareImg = async index => {
console.log('index:', index)
const el = document.getElementById(`capture${index}`)
console.log('el:', el)
// const canvasFalse = document.createElement('canvas')
const width = parseInt(window.getComputedStyle(el).width)
const height = parseInt(window.getComputedStyle(el).height)
console.log('width:', width, 'height:', height)
let canvas = await autoPicture(`capture${index}`, { width, height })
if (canvas) {
currentImg.value = canvas
show.value = true
// canvas为转换后的Canvas对象
let oImg = new Image()
oImg = currentImg.value // 导出图片
console.log(oImg)
var oA = document.createElement('a')
oA.download = '分享内容' // 设置下载的文件名,默认是'下载'
oA.href = oImg
document.body.appendChild(oA)
oA.click()
oA.remove() // 下载之后把创建的元素删除
}
}
</script>
<style lang="scss" scoped>
.capture {
width: 375px;
// height: 400px;
background: #ccc;
.bg {
width: 375px;
height: 600px;
}
}
</style>
更多推荐
已为社区贡献1条内容
所有评论(0)