This post explains how to use the package save-svg-as-png to download the png image of the contents in your svg element in your React component.
Create a basic React App as previously discussed in this post.
Create a component ImageWrapper as shown below:
import React from 'react'
export default class ImageWrapper extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<div>
<svg id={"svg-chart"} viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="100%" height="100%"/>
<circle cx="50%" cy="50%" r="2" fill="white"/>
</svg>
</div>
)
}
}
Install the following package in your App with the command:
npm install save-svg-as-png
Modify the code in your App.js file as shown below:
import React, { Component } from "react";
import "./App.css";
import ImageWrapper from "./components/ImageWrapper";
const saveSvgAsPng = require('save-svg-as-png')
const imageOptions = {
scale: 5,
encoderOptions: 1,
backgroundColor: 'white',
}
class App extends Component {
handleClick = () => {
saveSvgAsPng.saveSvgAsPng(document.getElementById('svg-chart'), 'shapes.png', imageOptions);
};
render() {
return (
<div className="App">
<ImageWrapper />
<br />
<button onClick={this.handleClick}>Download Image</button>
</div>
);
}
}
export default App;
Run the App with:
npm start
Click on the button Download Image to test.