Skip to main content

HTML5 Canvas Stage Serialization Tutorial

To serialize a stage with Konva, we can use the toJSON() method. The toJSON() method will return a JSON string that contains all of the node's attributes. Note that event handlers and images are not serializable.

import Konva from 'konva';

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

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

// create a shape
const circle = new Konva.Circle({
  x: 100,
  y: 100,
  radius: 50,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 3
});

layer.add(circle);

// add button
const button = document.createElement('button');
button.textContent = 'Serialize Stage';
document.body.appendChild(button);

button.addEventListener('click', () => {
  // serialize the stage
  const json = stage.toJSON();
  
  // show the result
  console.log(json);
  alert('Stage serialized! Check the console for the JSON string.');
});