typescript Html2canvas,但文本消失了

6l7fqoea  于 2023-01-03  发布在  TypeScript
关注(0)|答案(1)|浏览(719)

使用html2canvas将html转换为canvas,但导出结果中的文本会消失

<template>
    <div>
        <div id="exam">
            <h2>文本 Example</h2>
            <p>example example example example example example</p>
        </div>

        <br/><br/>
        <button @click="output">Print</button><br/><br/><br/>

        <p>Result:</p><br/>
        <div id="res"></div>
    </div>
</template>

<script lang="ts" setup>
import html2canvas from 'html2canvas'
const output = async () => {
    const dom = document.getElementById('exam')
    if (dom) {
        const cvs = await html2canvas(dom)
        document.getElementById('res')?.append(cvs)
    }
}
</script>

html2画布+ vue3 + ts + sass.

a7qyws3x

a7qyws3x1#

我想知道我有多经常看到开发者在vue组件中使用getElementByIdquerySelector。你应该确保使用所谓的template refs
您可以尝试下面的方法(我没有测试,但类似的方法应该可以工作)。

<div>
  <div ref="exam">
    <h2>文本 Example</h2>
    <p>example example example example example example</p>
  </div>
  <div ref="result"></div>
</div>
// inside script setup
import html2canvas from 'html2canvas'

const exam = ref<HTMLDivElement | null>(null);
const result = ref<HTMLDivElement | null>(null);
const cvs = ref<??? | undefined>();

const output = async () => {
  if (!exam.value || !result.value) return;
  
  // saving the cvs value in a ref variable
  // to keep it available on rerenderings.
  cvs.value = await html2canvas(exam.value)
}

// add a watcher that append the result
// in order to apply it every time the
// something changes because vue will
// empty the element each time you update something.
watch(
  cvs,
  (newCvs) => {
    if (!newCvs || !result.value) return;
    // clean the result element
    result.value.innerHTML = '';

    // append the new created cvs
    result.value.append(cvs);
  },
  { flush: 'post' },
)

相关问题