Echarts关系图如何自定义节点位置的思路

541 阅读2分钟

简介

本文主要介绍一Echarts中series.graph的使用中,需要对节点位置进行精准定位的一些思路

思路

我们先从官网中,简单graph这个图说起,这个图实现的option配置如下:

option = {
  title: {
    text: 'Basic Graph'
  },
  tooltip: {},
  animationDurationUpdate: 1500,
  animationEasingUpdate: 'quinticInOut',
  series: [
    {
      type: 'graph',
      layout: 'none',
      symbolSize: 50,
      roam: true,
      label: {
        show: true
      },
      edgeSymbol: ['circle', 'arrow'],
      edgeSymbolSize: [4, 10],
      edgeLabel: {
        fontSize: 20
      },
      data: [
        {
          name: 'Node 1',
          x: 300,
          y: 300
        },
        {
          name: 'Node 2',
          x: 800,
          y: 300
        },
        {
          name: 'Node 3',
          x: 550,
          y: 100
        },
        {
          name: 'Node 4',
          x: 550,
          y: 500
        }
      ],
      // links: [],
      links: [
        {
          source: 0,
          target: 1,
          symbolSize: [5, 20],
          label: {
            show: true
          },
          lineStyle: {
            width: 5,
            curveness: 0.2
          }
        },
        {
          source: 'Node 2',
          target: 'Node 1',
          label: {
            show: true
          },
          lineStyle: {
            curveness: 0.2
          }
        },
        {
          source: 'Node 1',
          target: 'Node 3'
        },
        {
          source: 'Node 2',
          target: 'Node 3'
        },
        {
          source: 'Node 2',
          target: 'Node 4'
        },
        {
          source: 'Node 1',
          target: 'Node 4'
        }
      ],
      lineStyle: {
        opacity: 0.9,
        width: 2,
        curveness: 0
      }
    }
  ]
};

在这个例子中,节点是通过x,y来进行定位的,这正式我们本文想要实现的方式。但是我们意识到,x,y的数值并不是一个绝对定位的值,也就是说,与坐标轴的坐标定位不同,在画布大小一定的情况下,(x,y)= (100,100) 的位置并不是一个固定的值。实际情况是怎么样呢?实际上echarts会根据x和y的最大值进行一个相对定位,让所有节点能尽量铺满画布。解释如下图:

这样的话,如果我们节点比较少的时候(假设节点的数量是动态变化的),我们的样式就会很难看了

但是知道布局是根据节点x,y的最大值去运算定位的,那么我们就能得出一个思路了,那我们搞4个x,y值比我们实际节点大的节点去把布局撑起来,然后我们的实际节点按照比例设置x,y的坐标,不用担心定位节点会影响显示,把opacity设置为0隐藏起来不就好了!

实现效果如下: