问题
I'm creating a custom label maker using Konvajs and everything was working perfectly until I tried to serialize the stage to JSON.
The user creates their custom label in three steps. The first step they select a template image from our library that has a masked area. The second step allows them to upload a personalized image that is placed behind the image that was loaded on the first step. There are external controls that allow the user to scale and move the image so it is rendered with in the masked area. The third step allows them to add text.
I want the user to be able to save their label to their library so they can use it again, but be able to modify any of the three steps. This means I need to serialize the stage to a JSON string, but the image attributes aren't saved in the JSON.
JSON String: {"attrs":{"width":500,"height":667,"id":"label-maker"},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{"name":"template"},"className":"Image"}]},{"attrs":{},"className":"Layer","children":[{"attrs":{"x":160,"y":41.5,"text":"[Enter Name Here]","fontSize":30,"fontFamily":"Calibri","fill":"#555","name":"textundefined","align":"center","draggable":true,"offsetX":114.22119140625},"className":"Text"}]}]}
I'm using the Konvajs toJSON() to serialize my stage.
function save() {
var json = stage.toJSON();
var dataURL = stage.toDataURL('image/png');
//alert(json);
$.ajax({
type: "POST",
url: "label-maker/image-handler.php?action=save",
data: {jsonFileText: json, image: dataURL},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
success: function () {
alert(" Done ! ");
}
});
}
回答1:
By default Konva
doesn't save information about image source to JSON. So you have to do this manually.
When you create Konva.Image
you can save its source as attribute:
// path is url or base64 string from user's input
imageNode.setAttr('src', path);
Then on deserialization you can load image data from source:
const stage = Konva.Node.create(json, 'container');
stage.find('Image').forEach((imageNode) => {
const src = imageNode.getAttr('src');
const image = new Image();
image.onload = () => {
imageNode.image(image);
imageNode.getLayer().batchDraw();
}
image.src = src;
});
来源:https://stackoverflow.com/questions/44835695/konvajs-serialize-stage-containing-images