uniapp 使用vue3+typescript 如何利用html2canvas生成图片

在微信小程序中无法获取dom,所以获取不到dom元素,那么解决办法是用内嵌一个h5页面的方式通过传值过去后,这个h5页面去获取dom生成图片
1、安装 html2canvas:

npm i html2canvas

2、引入 html2canvas:

import html2canvas from "html2canvas"
<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import dPrint from '@/components/dPrint/dPrint.vue'
import html2canvas from 'html2canvas'

const shellContainerRef = ref<any>()


const onclick = () => {
  if (shellContainerRef.value) {
    html2canvas(shellContainerRef.value.$el, {
      width: shellContainerRef.value.$el.clientWidth, //dom 原始宽度
      height: shellContainerRef.value.$el.clientHeight,
      scrollY: 0, // html2canvas默认绘制视图内的页面,需要把scrollY,scrollX设置为0
      scrollX: 0,
      useCORS: true, //支持跨域,但好像没什么用
      allowTaint: true, //允许跨域(默认false)
      scale: 1
    }).then((canvas) => {
      // 生成的ba64图片
      const base64Data = canvas.toDataURL('image/jpeg', 1)
    })
  }
}

onLoad((option:any) => {
  onclick()
})

</script>



 <template>
    <view class="content"  >
      <scroll-view :scroll-x="true" >
        <!-- 自己的组件 -->
        <d-print  ref="shellContainerRef" />
      </scroll-view>
    </view>
  </template>



  <style scoped>
  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  </style>

微信小程序跳转h5详情

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad} from '@dcloudio/uni-app'
const url = ref<any>('')
onLoad((option:any) => {
// /report/#/pages/reportDetail/index 是目标h5的页面 
  url.value = 'h5域名' + '/report/#/pages/reportDetail/index?id=' + option.id
})


</script>



<template>
  <view class="content"  >
    <web-view  :src="url"></web-view>
  </view>
</template>



<style scoped lang="less">

</style>

写的不好请理解, 如有不懂的或有问题可在下面留言

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值