在微信小程序中无法获取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>
写的不好请理解, 如有不懂的或有问题可在下面留言