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>

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值