Vignesh Bala
Vignesh Bala

Reputation: 919

Object's custom properties getting cleared in canvas to json

I have a canvas with multiple image objects. Every object has some custom attributes. I need to save this canvas as a json object into a database. I used following code to convert canvas into json.

canvasJson = JSON.stringify(canvas);

After converting, canvasJson can't have any custom attribute as well as it's values. It has only default attributes and it's values like width, height, opacity etc.

How can I fix that? Please suggest some right ways to solve this...

Edit

Following is my image object creation code to create image objects in canvas.

var imgObj = new Image();
var imgSrc = $IMAGE_URL;
imgObj.src = imgSrc;
var image = new fabric.Image(imgObj);
    image.set({
        left: 0,
        top: 0,
        angle: 0,
        padding: 0,
        cornersize: 0,
        lockMovementX: true,
        lockMovementY: true,
        lockRotation: true,
        elementId: $elementID,
        elementname: $elementName,
        elementstatus: $elementStatus,
        width: componentImageWidth,
        height: componentImageHeight
    });
    canvas.add(image);
    image.setCoords();
    canvas.renderAll();
    canvas.selection = false;
    canvas.renderAll();
    setObjectAction(image, false);

Converting the canvas into json using JSON.stringify(canvas); the elementId, elementname and elementstatus are missing. but default attributes are gets correctly.

How to fix this ?

Upvotes: 4

Views: 2730

Answers (1)

Szabó Csaba
Szabó Csaba

Reputation: 61

You can use fabric's canvas.toJson() or canvas.toDatalessJSON() functions, and you can include your custom properties as parameters like this:

var json = JSON.stringify(canvas.toDatalessJSON(['elementId','elementname', 'elementstatus']));

Upvotes: 6

Related Questions