跳到主要内容

HTML5 Canvas 舞台序列化教程

要使用 Konva 序列化舞台,可以使用 toJSON() 方法。 toJSON() 方法返回一个包含节点所有属性的 JSON 字符串。 事件处理程序和图像无法序列化。

import Konva from 'konva';

// Create wrapper with relative positioning
const stage = new Konva.Stage({
  container: 'container',
  width: 400,
  height: 400
});

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

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

layer.add(circle);

// Add button on top of stage
const button = document.createElement('button');
button.textContent = 'Serialize Stage';
button.style.position = 'absolute';
button.style.top = '10px';
button.style.left = '10px';
document.body.appendChild(button);

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