How to transform a stringified JSON object back into FabricJS (Deserialize)

In my JSON data, there is a canvas object with properties like type, originX, originY, and more.

{"type":"rect",
"originX":"left",
"originY":"top",
"left":100,
"top":100,
"width":200,
"height":200,
"fill":"blue",
"stroke":null,
"strokeWidth":1,
"strokeDashArray":null,
"strokeLineCap":"butt",
"strokeLineJoin":"miter",
"strokeMiterLimit":10,
"scaleX":1,"scaleY":1,
"angle":0,
"flipX":false,
"flipY":false,
"opacity”:1,
”shadow":null,
"visible":true,
"clipTo":null,
"backgroundColor":"",
"fillRule":"nonzero",
"globalCompositeOperation":"source-over",
"transformMatrix":null,
"skewX":0,
"skewY":0,
"rx":0,
"ry":0}

Is there a way to deserialize this object so I can add it back to the canvas using canvas.add()?

I prefer not to use canvas.loadFromJSON() because it will clear the current content on the canvas.

Answer №1

Unfortunately, the canvas.loadFromJSON() function clears the canvas before loading new objects. One workaround is to try the following approach:

var canvas;

        var json = '{"objects": [{"type":"rect", "left":100, "top":100, "width":200, "height":200, "fill":"blue"}]}';
        canvas = new fabric.Canvas('c');

        // Create an object that won't be overwritten when loading JSON
        var circle = new fabric.Circle({
            radius: 50, fill: 'green', left: 50, top: 50
        });
        canvas.add(circle);
        canvas.renderAll();

        // Parse JSON and add objects to canvas
        var jsonObj = JSON.parse(json);
        fabric.util.enlivenObjects(jsonObj.objects, function (enlivenedObjects) {
            enlivenedObjects.forEach(function (obj, index) {
                canvas.add(obj);
            });
            canvas.renderAll();
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>

<canvas id="c" width="600" height="400">    </canvas>

You can also use the following code to add just one object from JSON:

var json = '{"type":"rect", "left":100, "top":100, "width":200, "height":200, "fill":"blue"}';
        canvas = new fabric.Canvas('c');

        // Create an object to show that this doesn't get overwritten when we load the JSON
        var circle = new fabric.Circle({
            radius: 50, fill: 'green', left: 50, top: 50
        });
        canvas.add(circle);
        canvas.renderAll();

        // Parse JSON and single object to canvas
        var jsonObj = JSON.parse(json);
        fabric.util.enlivenObjects([jsonObj], function (enlivenedObjects) {
            canvas.add(enlivenedObjects[0]);
            canvas.renderAll();
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
    <canvas id="c" width="600" height="400"></canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to use Newtonsoft.Json.Linq.JObject as an argument for parsing JSON data?

I am currently working on implementing a JsonParser in C# by referring to a useful resource I found on Stack Overflow. As a newbie to C#, any assistance you can provide is greatly appreciated. One thing I'm curious about is whether a JObject can be p ...

Use JavaScript to smoothly navigate through a dialog box displayed within the window by scrolling down

Just starting to learn Javascript here. I've got a web page with an open dialog, and I'm looking to grammatically scroll down the dialog itself, not the main window. I attempted using: window.scrollTo(500,0); but this ended up scrolling the m ...

Tips for maintaining value in a PHP listbox

In my PHP page, I have a listbox that is generated from another listbox using the following code: <?php $myArray1 = $_POST['countryRF'];?> <select name='countryRF[]' id='countryRF' size='10&a ...

Tips for choosing and emphasizing specific lines in a dxf document with the help of three.js, dxf-parser, and three-dxf

Incorporating both the dxf-parser and three-dxf libraries, I am working on a webpage to display dxf drawings with the help of the three.js library. Although I was successful in loading the dxf file onto the webpage, I encountered difficulties in highligh ...

Leveraging API data within React: A step-by-step guide

I have a React application where I am making API calls. To manage these calls, I created a separate file called dataService.js to contain all the functions for interacting with the API. However, when trying to log the data in my component, I am getting a ...

The jQuery.find() method will still return an object even if there are no child elements in the DOM that match the criteria specified

I'm on the hunt for an element with the specific ID '' that resides within another element '', serving as its child. My search is powered by the $.find method. If the desired child object is located, I have a series of actions li ...

The UI Router template fails to inject despite state changes occurring

I've been attempting to create nested views, you can check out the Plunker demo https://embed.plnkr.co/oRMnMW4QoWwhSkm9maHf/. The state is updating as expected but the template remains the same. Could someone please point out where I may have gone wr ...

Change the value of a div element from a decimal number to an integer

Suppose we have <div id="mydiv>>111</div> in an HTML document and the intention is to extract this number using GetElementbyID(myid).value and convert it to an integer Attempts have been made with ParseInt, ParseInt(x, 10), Number(x).... ...

How to modify and remove a card element in semantic UI with react coding

I have recently created some cards and now I want to enhance the user experience by allowing them to edit the card data and delete the card altogether if they choose to do so. For the deletion functionality, here is an example of deleting a card using jQu ...

The iPhone numerical keyboard continues to appear even after submitting a form within an iFrame on iOS Safari

Our React web application incorporates a Stripe element form for the checkout process, which involves injecting an iFrame form onto the website. An issue arises when using iOS Safari – the credit card keyboard pops up when a user interacts with the Strip ...

What is the best way to start up node.js and react?

Can you help me with running a server node js and a react app simultaneously? Here is my package.json { "name": "mon-app", "version": "0.1.0", "private": true, "dependencies": { "express": "^4.17.1", "react": "^16.14.0", "react-dom": ...

Setting up your NODEJS Express Server to handle POST requests: A Step-by-Step Guide

I am currently developing a quiz app that utilizes the Gemini API to generate questions. The frontend of the app is built using HTML, CSS, and Vanilla JavaScript, while the backend is powered by Node.JS with Express. Every time I make a fetch request usin ...

Setting filters programmatically in Mui X Data Grid

I am currently working with the MUI Data Grid (pro version) and I am looking to implement checkboxes in the sidebar to filter different columns. Consider three columns: * Column Letters: ['a', 'b', 'c', 'd', etc.] * ...

When is it necessary to create a script that will dynamically apply a .current class (similar to active) to an element?

Creating a navigation menu 'component' - after researching some examples, I noticed that many of them utilize controllers and JavaScript to dynamically include a .current (active-like class). One example is the navigation bar on https://www.googl ...

Comparing npm start and running the app with node app.js

I'm brand new to exploring the world of Node and understanding the basics of app development. I find it interesting how these two commands seem to have a similar output: node app.js --compared to-- npm start Both commands appear to continue "l ...

What offers better performance: XmlHttpRequest response in HTML or JSON format?

When it comes to a highly AJAX-enabled website, the content of the web page can be updated partially using AJAX. This basically involves changing HTML tags or parts of the web page. So, when faced with this situation, we must decide between two approaches ...

Python JSON Schema Validation for Repeated JSON Responses

When attempting to validate my Json schema with my Json response using the Validate function from Jsonschema.validate, I am encountering no success. Interestingly, it shows that the two match on . Check out the Json Schema below: { "KPI" ...

Using XmlHttpRequest to send a zipped file created with JSZip in JavaScript

I'm currently working on a web application where I need to generate a set of files based on user input, zip them using the JSZip library, and then post these files to a server using XHR. The code snippet for this functionality is as follows: var cont ...

Dealing with router parameters of an indefinite number in Angular 5: A comprehensive guide

Is there a method to efficiently handle an unknown number of router parameters in a recursive manner? For instance: We are dealing with product categories that may have subcategories, which can have their own subcategories and so on. There are a few key ...

Tips for managing player rounds updates

How can I make the number of rounds increase by 1 every time a card is clicked, rather than jumping to 4 and staying there? The initial value is set at 'let rounds = 0;' in my code. <!DOCTYPE html> <html lang="en"> < ...