简体   繁体   English

以递归的方式在Fabric.js中绘制形状

[英]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..). 我必须在js中制作一个网络地图,其中的组件(等)中包含一些组件。 I use canvas to do this with the Fabric.js library. 我使用canvas通过Fabric.js库执行此操作。

I get a json from an api like this : 我从这样的api获取json:

{
    "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: 基本上,您需要确定JSON对象的属性是否为数组,然后再次调用递归函数,否则检查属性名称是否为“ 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(); 请记住使用canvas.renderAll(); function after the recursion function as long as it will be better performance. 函数递归后,只要具有较好的性能即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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