我目前有一个Recharts组件,我想将其导出为PNG文件。
<LineChart id="currentChart" ref={(chart) => this.currentChart = chart} width={this.state.width} height={this.state.height} data={this.testData} margin={{top: 5, right: 30, left: 20, bottom: 5}} > <XAxis dataKey="name"/> <YAxis/> <CartesianGrid strokeDasharray="3 3"/> <Tooltip/> <Legend /> <Line type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{r: 8}}/> <Line type="monotone" dataKey="uv" stroke="#82ca9d"/> </LineChart>
但是我不确定库是否直接支持此功能。
我有一个想法,涉及使用画布和2D渲染上下文使我接近解决方案,如MDN所述
但是,我不确定将HTML元素(或React组件)呈现为画布以实现此解决方案的通用方法。
我可能会犯错,对此我将不胜感激!
通过研究“图表”组件,我能够解决我的问题。图表在包装器下呈现为SVG,因此我要做的就是正确转换以保存为HTML或SVG
// Exports the graph as embedded JS or PNG exportChart(asSVG) { // A Recharts component is rendered as a div that contains namely an SVG // which holds the chart. We can access this SVG by calling upon the first child/ let chartSVG = ReactDOM.findDOMNode(this.currentChart).children[0]; if (asSVG) { let svgURL = new XMLSerializer().serializeToString(chartSVG); let svgBlob = new Blob([svgURL], {type: "image/svg+xml;charset=utf-8"}); FileSaver.saveAs(svgBlob, this.state.uuid + ".svg"); } else { let svgBlob = new Blob([chartSVG.outerHTML], {type: "text/html;charset=utf-8"}); FileSaver.saveAs(svgBlob, this.state.uuid + ".html"); } }
我正在使用FileSaver.js作为保存提示。