Skip to main content

How to export a canvas into an image from react-konva?

How to save a drawing from react-konva?

To export any Konva node into an image you can either use the node.toDataURL() or the node.toImage() API. Take a look into the vanilla Konva image export demo.

You will need to use the Refs API to access a Konva node directly in order to call these methods.

import React, { Fragment } from 'react';
import { Stage, Layer, Rect } from 'react-konva';

// function from https://stackoverflow.com/a/15832662/512042
function downloadURI(uri, name) {
var link = document.createElement('a');
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}

const App = () => {
const width = window.innerWidth;
const height = window.innerHeight;

const stageRef = React.useRef(null);

const handleExport = () => {
const uri = stageRef.current.toDataURL();
console.log(uri);
// we also can save uri as file
downloadURI(uri, 'stage.png');
};

return (
<Fragment>
<button onClick={handleExport}>Click here to export stage as image</button>
<Stage width={width} height={height} ref={stageRef}>
<Layer>
<Rect x={0} y={0} width={80} height={80} fill="red" />
<Rect x={width - 80} y={0} width={80} height={80} fill="red" />
<Rect
x={width - 80}
y={height - 80}
width={80}
height={80}
fill="red"
/>
<Rect x={0} y={height - 80} width={80} height={80} fill="red" />
</Layer>
</Stage>
</Fragment>
);
};

export default App;

Before you raise the pixel ratio

Browsers cap canvas width, height, and total area, so a high pixelRatio can return a blank image rather than an error. See high quality export for the limits and the ways around them.