How can i download the image? #84
-
Hi! I'm a beginner developer who doesn't know much about React. I want to save the completed canvas in image(.png) format. const [dataURI, setDataURI] = useState('');
const [exportImageType, setexportImageType] = useState('png');
...
const imageExportHandler = async () => {
const exportImage = canvasRef.current?.exportImage;
if (exportImage) {
const exportedDataURI = await exportImage(exportImageType);
setDataURI(exportedDataURI);
}
const downloadImage = document.createElement('a');
downloadImage.href = dataURI;
downloadImage.download = 'paint_image';
downloadImage.click();
};
...
return (
...
<FontAwesomeIcon
className={styles.icon_share}
icon={faDownload}
onClick={() => imageExportHandler()}
/>
...
) How can I download the image from PC and mobile? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @beurmuz, Your React code looks good! The only issue with your code is that you have set the state using https://codesandbox.io/s/nifty-gauss-zk8xtt?file=/src/App.js |
Beta Was this translation helpful? Give feedback.
Hey @beurmuz,
Your React code looks good! The only issue with your code is that you have set the state using
setDataURI
and immediately accessed thedataURI
state value. Setting state in react is an asynchronous and batched operation so you can't immediately access the value that you have set. So instead you can use theexportedDataURI
variable to download the image. I made an example in the link below, you can use that. Let me know if you any more info!https://codesandbox.io/s/nifty-gauss-zk8xtt?file=/src/App.js