javascript - 将组件重新绘制为 PNG

标签 javascript reactjs canvas recharts

我目前有一个 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>;

但我不确定图书馆是否直接支持这一点。

我有一个想法,涉及使用 Canvas 和 2D 渲染上下文让我接近解决方案,如 MDN 中所述。

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

我可能做错了这一切,我将不胜感激!

最佳答案

此函数将 SVG 元素作为输入并转换为 image/png 数据:

export const svgToPng = (svg, width, height) => {

    return new Promise((resolve, reject) => {

        let canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        let ctx = canvas.getContext('2d');

        // Set background to white
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, width, height);

        let xml = new XMLSerializer().serializeToString(svg);
        let dataUrl = 'data:image/svg+xml;utf8,' + encodeURIComponent(xml);
        let img = new Image(width, height);

        img.onload = () => {
            ctx.drawImage(img, 0, 0);
            let imageData = canvas.toDataURL('image/png', 1.0);
            resolve(imageData)
        }

        img.onerror = () => reject();

        img.src = dataUrl;
    });
};

以及如何访问 Recharts SVG 元素?此代码片段允许您在当前可见 DOM 之外呈现任何图表并使用它的 SVG:

const exportChart = () => {

    // Output image size
    const WIDTH = 900;
    const HEIGHT = 250;

    const convertChart = async (ref) => {

        if (ref && ref.container) {
            let svg = ref.container.children[0];
            let pngData = await svgToPng(svg, WIDTH, HEIGHT);
            console.log('Do what you need with PNG', pngData);
        }
    };

    const chart = <LineChart data={...} width={WIDTH} height={HEIGHT}
        ref={ref => convertChart(ref)} />;

    // Render chart component into helper div
    const helperDiv = document.createElement('tmp');
    ReactDOM.render(chart, helperDiv);
}

关于javascript - 将组件重新绘制为 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45086005/

相关文章:

javascript - iOS 上 Safari 中的 shiftKey

javascript - 我怎样才能通过使用 HTML、CSS 和 JavaScript 来实现这样的效果(参见内部)?

node.js - 服务器端渲染 (Next.js) 和静态站点渲染 (Gatsby.js) 有什么区别?

javascript - React中保存编辑好的表单后自动刷新页面

javascript - 从 base 64 字符串绘制 Canvas 图片时出错

html - 最佳实践, Canvas 的最大宽度

d3.js - 传单.js : too slow with custom svg markers (and a lot of points)

javascript - For循环未达到5

javascript - 从数组中随机选择然后将选择分配给变量

css - 无法使用 webpack 设置 React 组件的样式