konvajs serialize stage containing images

℡╲_俬逩灬. 提交于 2019-12-11 06:58:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!