Recharts component to PNG

前端 未结 3 2003
梦如初夏
梦如初夏 2021-01-13 00:13

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

                    

        
3条回答
  •  日久生厌
    2021-01-13 00:35

    This function takes SVG element on input and transforms to image/png data:

    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;
        });
    };
    

    And how to access the Recharts SVG element? This code snippet allows you to render any Chart outside of your current visible DOM and use it's 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 =  convertChart(ref)} />;
    
        // Render chart component into helper div
        const helperDiv = document.createElement('tmp');
        ReactDOM.render(chart, helperDiv);
    }
    

提交回复
热议问题