简体   繁体   中英

Draw shapes in a shape recursively Fabric.js

I have to make a network map in js in which there are components included in component (etc..). I use canvas to do this with the Fabric.js library.

I get a json from an api like this :

{
    "name": "BAY_01",
    "type": "Bay",
    "_links": [{
        "name": "SERVER_01",
        "type": "Server",
        "_links": [{
            "name": "CPU"
        }, {
            etc...
        }],
    }]
}

I think the best way to implement the draw of these components is to make it recursive but I don't know how to do this.

Can anyone help me to solve my issue?

Here is an example of using recursion by name . Basically you need to determine if a property of the JSON object is an array then call recursion function again, else check if property name is "name" then call function to draw shape by name:

 var obj = { "name": "BAY_01", "type": "Bay", "_links": [{ "name": "SERVER_01", "type": "Server", "_links": [{ "name": "CPU" }, { "name": "SERVER_02", "type": "Server", "_links": [{ "name": "CPU2" }] }] }] }; function goThroughtObject(obj, name) { var key; if (obj instanceof Array) { return obj.map(function(value) { if (typeof value === "object") { goThroughtObject(value, name) } return value; }) } else { for (key in obj) { if (obj.hasOwnProperty(key)) { if (key === name){ drawByName(obj[key]); } if (obj[key] instanceof Array || (obj[key] !== null && obj[key].constructor === Object)) { goThroughtObject(obj[key], name); } } } } }; //implement fabricjs logic in this function function drawByName (name) { console.log("Fabricjs will draw a: " + name); } goThroughtObject(obj, 'name'); 

Please remember to use canvas.renderAll(); function after the recursion function as long as it will be better performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM