Skip to main content

Canvas Screenshot — Export HTML5 Canvas as Image with JavaScript

To take a screenshot of your canvas and export it as an image with Konva, use the toDataURL() method. It returns the data URL directly for every node type, including Stage. You can pass in a mime type such as image/jpeg and a quality value that ranges between 0 and 1. You can also capture screenshots of specific nodes, including layers, groups, and shapes.

Note: The toDataURL() method requires that any images drawn onto the canvas are hosted on a web server with the same domain as the code executing it. If this condition is not met, a SECURITY_ERR exception is thrown.

Instructions: Drag and drop the rectangle and then click on the save button to get the composite data url and open the resulting image in a new window.

import Konva from 'konva';

const stage = new Konva.Stage({
container: 'container',
width: 400,
height: 400
});

const layer = new Konva.Layer();
stage.add(layer);

// create draggable rectangle
const rect = new Konva.Rect({
x: 100,
y: 100,
width: 100,
height: 100,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true
});

layer.add(rect);

// add button
const button = document.createElement('button');
button.textContent = 'Save as Image';
document.body.appendChild(button);

button.addEventListener('click', () => {
// get data URL with default settings
const dataURL = stage.toDataURL();

// open in new window
const win = window.open();
win.document.write(`<img src="${dataURL}" alt="Stage"/>`);

// you can also save with different settings
const jpegURL = stage.toDataURL({
mimeType: 'image/jpeg',
quality: 0.8
});
console.log('JPEG URL:', jpegURL);
});