vue3 使用html2canvas
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
免费下载资源
·
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>
GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891
Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
更多推荐
已为社区贡献2条内容
所有评论(0)