我在 Vue 3 中用 D3.js 编写了几个图表组件,并且有一个单独的组件,它是一个使用 html2canvas 将单个图表导出为 PNG 的按钮。导出工作正常,但我使用 Poppins 作为图表中图例和轴标签等内容的字体,但这没有正确导出。
这是我导出图表的代码:
const vm = this
html2canvas(document.getElementById(this.chartID), {
scale: vm.exportImageScale,
scrollY: -window.scrollY,
backgroundColor: '#121111',
}).then((canvas) => {
downloadLink(canvas.toDataURL(), `${this.downloadName}.png`)
})
我尝试使用 html-to-image 相反,但最终在尝试访问字体时遇到了很多 429 错误。
为了确保 Poppins 字体显示在图表中,您需要在捕获图表之前先加载字体。
const vm = this
const font = new FontFaceObserver('Poppins');
font.load().then(() => {
html2canvas(document.getElementById(vm.chartID), {
scale: vm.exportImageScale,
scrollY: -window.scrollY,
backgroundColor: '#121111',
useCORS: true,
}).then((canvas) => {
downloadLink(canvas.toDataURL(), `${vm.downloadName}.png`);
});
}).catch((error) => {
console.error('Error loading font:', error);
});