Skip to main content

Load HTML5 Canvas Stage from JSON Tutorial

To load a complex stage that originally contained images and event bindings using Konva, we need to create a stage node using Konva.Node.create(), and then set the images and event handlers with the help of selectors using the find() method. Images and event handlers must be manually set because they aren't serializable.

That methods works for small apps. For more complex cases take a look into Best Practices

import Konva from 'konva';

// JSON string from a previous save
const json = '{"attrs":{"width":578,"height":200},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{"x":100,"y":100,"sides":6,"radius":70,"fill":"red","stroke":"black","strokeWidth":4},"className":"RegularPolygon"}]}]}';

// create node using json string
const stage = Konva.Node.create(json, 'container');

// get reference to the hexagon
const hexagon = stage.findOne('RegularPolygon');

// bind events
hexagon.on('click', () => {
  hexagon.fill(Konva.Util.getRandomColor());
  stage.find('Layer').first().draw();
});