我的问题是html2canvas无法呈现自定义字体。我在项目中使用样式化组件和react-vis。当我在受限组件中使用系统字体时,html2canvas可以完美运行,但是当我尝试使用自定义字体时,它将呈现默认的系统字体。 有我的代码,生成png:
this.generateImage = () => {
const chart = this.myRef.current;
const chartComponent = this.chartComponentRef.current;
const chartComponentSizes = chartComponent.getBoundingClientRect();
html2canvas(chart, {
foreignObjectRendering: true,
useCORS: true,
allowTaint: true,
imageTimeout: 5000,
}).then((canvas) => {
const croppedCanvas = document.createElement('canvas');
const croppedCanvasContext = croppedCanvas.getContext('2d');
croppedCanvas.width = chartComponentSizes.width + 20;
croppedCanvas.height = chartComponentSizes.height + 20;
croppedCanvasContext.drawImage(
canvas,
0,
0,
chartComponentSizes.width + 20,
chartComponentSizes.height + 20,
0,
0,
chartComponentSizes.width + 20,
chartComponentSizes.height + 20,
);
this.setState({ screenCapture: croppedCanvas.toDataURL() });
const element = document.createElement('a');
element.setAttribute('href', croppedCanvas.toDataURL());
element.setAttribute('download', `${new Date().toLocaleDateString()}-img.png`);
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
});
};