Fabric.js - how to save canvas on server with custom attributes

后端 未结 5 1699
梦毁少年i
梦毁少年i 2020-11-27 09:45

I\'d like to be able to save the current canvas\' state to a server-side database, probably as a JSON string, and then later restore it with loadFromJSON. Typic

5条回答
  •  温柔的废话
    2020-11-27 10:42

    I had the same issue but I didn't want to extend the fabric.js classes.

    I wrote a function that takes the fabric canvas in parameter and returns a stringified version with my special attributes:

    function stringifyCanvas(canvas)
    {
        //array of the attributes not saved by default that I want to save
        var additionalFields = ['selectable', 'uid', 'custom']; 
    
        sCanvas = JSON.stringify(canvas);
        oCanvas = JSON.parse(sCanvas) ;
        $.each(oCanvas.objects, function(n, object) {
            $.each(additionalFields, function(m, field) {
                oCanvas.objects[n][field] = canvas.item(n)[field];
            });
        });
    
        return JSON.stringify(oCanvas);     
    }
    

    The special attributes seems properly imported when I use canvas.loadFromJSON(), I'm using fabric 1.7.2.

提交回复
热议问题