uniapp-app/components/MyHtml2canvas.vue
2026-02-02 17:44:10 +08:00

95 lines
2.1 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<!-- domId 是要截图的容器 id -->
<view class="my-html2canvas" :prop="domId" :change:prop="h2cRender.watchDomId">
<!-- 用于触发 renderjs 截图 -->
<text :prop="expOver" :change:prop="h2cRender.watchExpOver"></text>
</view>
</template>
<script>
export default {
props: {
domId: {
type: String,
required: true
}
},
data() {
return {
expOver: 0
}
},
methods: {
// 业务层调用这个方法开始截图
h2cRenderDom() {
// #ifdef H5
// H5 直接在当前环境(有 DOM里跑 renderDom
this.$emit('renderDomInH5')
// #endif
// #ifndef H5
// 非 H5APP 等)通过 expOver 触发 renderjs 中的截图逻辑
this.expOver++
// #endif
},
// renderjs 截图完成后会 callMethod 回调到这里
renderOver(base64) {
this.$emit('renderOver', base64)
}
}
}
</script>
<!-- renderjs 只能内联 -->
<script module="h2cRender" lang="renderjs">
import html2canvas from 'html2canvas'
export default {
data() {
return {
domIdValue: ''
}
},
methods: {
async renderDom() {
try {
const el = document.getElementById(this.domIdValue)
if (!el) {
console.error('[MyHtml2canvas] dom 未找到,请检查 domId', this.domIdValue)
return
}
const canvas = await html2canvas(el, {
width: el.offsetWidth,
height: el.offsetHeight,
x: 0,
y: 0,
useCORS: true,
scale: 2
})
const base64 = canvas.toDataURL('image/png', 1)
this.$ownerInstance.callMethod('renderOver', base64)
} catch (err) {
console.error('[MyHtml2canvas] html2canvas 失败:', err && err.message)
}
},
// script 部分通过 :prop 传入 domId
watchDomId(newVal) {
this.domIdValue = newVal
},
// expOver 变化时触发渲染
watchExpOver(newVal) {
if (newVal !== 0) {
this.renderDom()
}
}
}
}
</script>
<style>
.my-html2canvas {
position: relative;
}
</style>