HTML5 Canvas 阶段序列化教程
要使用 Konva 序列化一个阶段,我们可以使用 toJSON()
方法。
toJSON()
方法将返回一个包含所有节点属性的 JSON 字符串。
请注意,事件处理程序和图像是不可序列化的。
- Vanilla
- React
- Vue
import Konva from 'konva'; // 创建具有相对定位的封装 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); // 在舞台上方添加按钮 const button = document.createElement('button'); button.textContent = '序列化阶段'; 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('阶段已序列化!请检查控制台以获取 JSON 字符串。'); });
注意: 尽管在 React 中直接序列化阶段可行,但通常被认为是反模式。在 React 应用程序中,您应该单独管理应用程序状态,并序列化该状态,而不是序列化阶段。
import { Stage, Layer, Circle } from 'react-konva'; import { useRef, useState } from 'react'; const App = () => { const stageRef = useRef(null); const [circle, setCircle] = useState({ x: 100, y: 100, radius: 50, fill: 'red', stroke: 'black', strokeWidth: 3 }); const handleSerialize = () => { // 在实际应用程序中,优先保存应用状态,而不是阶段 JSON const json = JSON.stringify({ shapes: [circle] }); console.log('序列化状态:', json); alert('状态已序列化!请检查控制台以获取 JSON 字符串。'); }; return ( <div style={{ position: 'relative' }}> <button onClick={handleSerialize} style={{ position: 'absolute', top: '10px', left: '10px', zIndex: 1 }} > 序列化 </button> <Stage width={400} height={400} ref={stageRef}> <Layer> <Circle {...circle} draggable onDragEnd={(e) => { setCircle({ ...circle, x: e.target.x(), y: e.target.y() }); }} /> </Layer> </Stage> </div> ); }; export default App;
注意: 尽管在 Vue 中直接序列化阶段可行,但通常被认为是反模式。在 Vue 应用程序中,您应该使用响应式数据管理应用程序状态,并序列化该状态,而不是序列化阶段。
<template> <div style="position: relative"> <button @click="handleSerialize" style="position: absolute; top: 10px; left: 10px; z-index: 1" > 序列化 </button> <v-stage :config="stageSize"> <v-layer> <v-circle :config="circle" draggable @dragend="handleDragEnd" /> </v-layer> </v-stage> </div> </template> <script setup> import { ref } from 'vue'; const stageSize = { width: 400, height: 400 }; const circle = ref({ x: 100, y: 100, radius: 50, fill: 'red', stroke: 'black', strokeWidth: 3 }); const handleSerialize = () => { // 在实际应用程序中,优先保存应用状态,而不是阶段 JSON const json = JSON.stringify({ shapes: [circle.value] }); console.log('序列化状态:', json); alert('状态已序列化!请检查控制台以获取 JSON 字符串。'); }; const handleDragEnd = (e) => { const node = e.target; circle.value = { ...circle.value, x: node.x(), y: node.y() }; }; </script>