konva-conver
v1.0.8
Published
对Konva.Stage进行序列化和反序列化
Downloads
9
Maintainers
Readme
You're Welcome
Let us to see a Demo where is down
import React, { useEffect } from 'react';
import Konva from "konva"
import { Parser, Serializer } from "../konva-conver"
let tempStage;
function FooComponent() {
useEffect(() => {
}, []);
function init() {
var stage = new Konva.Stage({
container: 'konvas',
width: window.innerWidth,
height: window.innerHeight
});
var layer = new Konva.Layer();
var rect1 = new Konva.Rect({
x: 20,
y: 20,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
layer.add(rect1);
const src1 = "https://img0.baidu.com/it/u=3598947434,1699332782&fm=253&fmt=auto&app=138&f=PNG?w=1085&h=500";
const src2 = "https://img1.baidu.com/it/u=4184930606,3373942494&fm=253&fmt=auto&app=120&f=JPEG?w=545&h=363";
Promise.all([loadImage(src1), loadImage(src2)]).then((resList) => {
resList.forEach((img, index) => {
let yoda = new Konva.Image({
x: index * 60,
y: index * 30,
image: img,
width: img.width,
height: img.height,
draggable: true,
scalable: true
});
let tr = new Konva.Transformer();
layer.add(tr);
tr.attachTo(yoda);
layer.draw();
layer.add(yoda)
})
})
stage.add(layer);
tempStage = stage
}
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image()
img.src = src;
img.crossOrigin = 'anonymous';
img.onload = function () {
resolve(img)
}
img.onerror = function (e) {
console.error(e)
reject(img)
}
})
}
function parse(string) {
const parser = new Parser(string);
parser.parseTo("konvas")
}
const handleSerialize = (stage) => {
const serializer = new Serializer(stage, {
isBase64Image: true
})
const str = serializer.serialize()
console.log(str)
localStorage.setItem("str", str)
}
return (<div>
<button onClick={() => {
init()
}}>init canvas (first click)</button>
<button style={{margin:"0 10px"}} onClick={() => {
handleSerialize(tempStage)
}}>serialize (second click)</button>
<button onClick={() => {
const str = localStorage.getItem("str")
parse(str)
}}>parse to container( to click after when refreshed the page )</button>
<div id="konvas"></div>
</div>)
}
export default FooComponent