You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用html2canvas转换HTML为Canvas时导出结果文本消失

Vue3+TS+Sass下html2canvas转换DOM时文本消失的解决方案

针对你遇到的html2canvas导出Canvas后文本消失的问题,给出几个实际可行的解决办法:

1. 等待字体加载完成再执行渲染

如果页面使用了自定义字体或非系统默认字体,html2canvas可能在字体未加载完成时就开始渲染,导致文本无法显示。可以通过document.fonts.ready确保字体加载完毕:

const output = async () => {
    const dom = document.getElementById('exam')
    if (dom) {
        // 等待所有字体加载完成
        await document.fonts.ready;
        const cvs = await html2canvas(dom)
        document.getElementById('res')?.append(cvs)
    }
}

2. 明确指定DOM元素的字体

有时Sass的样式继承会导致html2canvas无法正确识别字体,直接给目标DOM设置明确的字体属性:

#exam {
    font-family: "Microsoft YaHei", Arial, sans-serif; // 替换为你实际使用的字体
}

3. 关闭硬件加速相关样式

如果你的Sass样式中使用了transform: translateZ(0)这类开启硬件加速的属性,可能会干扰html2canvas的渲染,移除这类样式:

// 移除类似这样的硬件加速样式
#exam {
    // transform: translateZ(0);
}

4. 调整html2canvas的配置项

添加scale参数提高渲染精度,同时确保基础配置正确:

const cvs = await html2canvas(dom, {
    scale: 2, // 提高渲染分辨率,避免模糊或文本丢失
    useCORS: true,
    allowTaint: false
})

快速验证步骤

  • 先替换为系统默认字体(比如Arial)测试,排除自定义字体加载问题
  • 检查目标DOM是否存在display: none、opacity: 0这类隐藏属性
  • 升级html2canvas到最新版本,避免旧版本的Vue3兼容性bug

内容的提问来源于stack exchange,提问作者沙荔枝

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:20:36