将组件重新映射到PNG [英] Recharts component to PNG

查看:112
本文介绍了将组件重新映射到PNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个Recharts组件,我想将其导出为PNG文件。

I currently have a Recharts component that I would like to export as a PNG file.

                    <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>

但我不确定库是否直接支持。

but I'm unsure if this is directly supported by the library.

我有一个想法,包括使用画布和2D渲染上下文让我接近解决方案,如 MDN

I have an idea that involves using a canvas and a 2D rendering context to get me close to a solution, as outlined on MDN

但是,我不确定是否通用将HTML元素(或React Component)呈现为画布以实现此解决方案的方法。

However, I'm not sure of a generic way to render an HTML element (or React Component) as a canvas to implement this solution.

我可能会说这一切都错了,我很感激修正!

I might be going about this all wrong, and I would appreciate the correction!

推荐答案

我能够通过深入研究Recharts组件来解决我的问题。 Recharts在包装器下呈现为SVG,因此我所要做的就是正确转换为另存为HTML或SVG

I was able to solve my problem by delving into the Recharts component. Recharts renders as an SVG under a wrapper so all I had to do was convert properly to save as both HTML or 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 用于保存提示。

I am using FileSaver.js for the save prompt.

这篇关于将组件重新映射到PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆