const exportElement = async () => {
// 1. 注入修复样式
const style = document.createElement('style');
style.id = 'export-fix-style';
document.head.appendChild(style);
if (style.sheet) {
style.sheet.insertRule('* { box-sizing: border-box !important; }', 0);
style.sheet.insertRule('img { display: inline-block !important; }', 1);
style.sheet.insertRule('div { box-sizing: border-box !important; line-height: 1.2 !important; }', 2);
style.sheet.insertRule('span { line-height: 1.2 !important; }', 3);
}
try {
// 2. 等待资源加载(图片+字体)
await Promise.all([
...document.images.map(img =>
img.complete ? Promise.resolve() : new Promise(resolve => {
img.onload = img.onerror = resolve;
})
),
document.fonts.ready // 等待字体加载完成
]);
// 3. 执行截图(关键配置见下文)
const canvas = await html2canvas(element, {
scale: 3, // 高清缩放
foreignObjectRendering: false, // 禁用 foreignObject,使用传统渲染更稳定
useCORS: true, // 允许跨域图片
allowTaint: true // 允许污染画布(配合 useCORS 处理跨域)
});
return canvas.toDataURL('image/png', 1.0); // 返回 PNG 数据
} finally {
// 4. 清理临时样式(确保异常时也移除)
document.getElementById('export-fix-style')?.remove();
}
};