You need to enable JavaScript to run this app. 如何在cytoscape.js的circle布局中将指定节点固定在圆心
优惠活动
大模型
产品
解决方案
定价
更多

如何在cytoscape.js的circle布局中将指定节点固定在圆心

Cytoscape.js circle布局固定代谢物节点到圆心实现方案

实现逻辑

Cytoscape内置的circle布局默认会将所有参与计算的节点均匀排列在圆周上,要实现代谢物节点固定在圆心,只需要两步操作:

  • 提前将type为met的节点定位到画布中心并锁定位置,避免布局运行时修改它的坐标
  • 配置circle布局的过滤规则,仅让type为prot的蛋白节点参与圆周排列计算

完整修改后代码

<script>
      var cy = cytoscape({
        container: document.getElementById('cy'),
        elements: [
          // nodes
          { data: { id: 'a', type: "met" } },
          { data: { id: 'b', type: "prot" } },
          { data: { id: 'c', type: "prot" } },
          { data: { id: 'd', type: "prot" } },
          { data: { id: 'e', type: "prot" } },
          { data: { id: 'f', type: "prot" } },
          // edges
          {
            data: {
              id: 'ab',
              source: 'a',
              target: 'b'
            }
          },
          {
             data: {
              id: 'ae',
              source: 'a',
              target: 'e'
            }
          }, 
          {
            data: {
              id: 'cd',
              source: 'c',
              target: 'd'
            }
          },
          {
            data: {
              id: 'ef',
              source: 'e',
              target: 'f'
            }
          },
          {
            data: {
              id: 'ac',
              source: 'a',
              target: 'c'
            }
          },
          {
            data: {
              id: 'be',
              source: 'b',
              target: 'e'
            }
          }
        ], 
        style: [
          {
            selector: 'node[type="prot"]',
            style: {
              'shape': 'circle',
              'background-color': 'red',
              label: 'data(id)'
            }
          },
          {
            selector: 'node[type="met"]',
            style: {
              'shape': 'square',
              'background-color': 'blue',
              label: 'data(id)'
            }
          }
        ]
      });

      // 新增代码:定位代谢物节点到圆心并锁定
      const metNode = cy.$('node[type="met"]').first();
      const canvasCenter = cy.extent().center();
      metNode.position({
        x: canvasCenter.x,
        y: canvasCenter.y
      });
      metNode.lock(); // 锁定位置,布局运行不会修改该节点坐标

      // 修改布局配置,新增filter规则
      cy.layout({
        name: 'circle',
        animate: true,
        filter: function(ele) {
          // 仅蛋白节点参与圆形布局计算
          return ele.isNode() && ele.data('type') === 'prot';
        }
      }).run();
</script>

注意事项

  • 如果存在多个type为met的代谢物节点,可以根据业务需求自行调整每个节点的固定位置,或者对代谢物节点单独使用其他布局渲染
  • 节点锁定后如果需要手动拖动调整位置,需要先调用metNode.unlock()解锁

内容的提问来源于stack exchange,提问作者Santosh Behera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 18:12:02