ANTV/G6 怎么按条件自定义节点颜色(Graphin)


一.当需求需要根据节点的类型来显示不同的颜色时,我们就可以自定义节点的颜色,通过后台返回的数据判断不同类型的节点显示不同的颜色


 // 以下是自定义节点颜色重点 // 根据后台返回的数据,flag 为 'b' 的节点显示 “#fff” 颜色,其他默认显示 fill: “#ea7171” 颜色 graph.node(node => { if (node.flag === 'b') { return { style:{ fill: '#fff', stroke: '#ea7171' } } } return { style: { fill: '#2db7f5', stroke: '#ea7171' } } }); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

在这里插入图片描述
二、完整代码

import G6 from '@antv/g6'; const data = { nodes: [ { id: '0', label: '0', flag: 'b', }, { id: '1', label: '1', flag: 'b', }, { id: '2', label: '2', flag: 'a', }, { id: '3', label: '3', flag: 'b', }, { id: '4', label: '4', flag: 'a', } ], edges: [ { source: '0', target: '1', }, { source: '0', target: '2', }, { source: '0', target: '3', }, { source: '0', target: '4', }, ], }; const width = document.getElementById('container').scrollWidth; const height = document.getElementById('container').scrollHeight || 500; const graph = new G6.Graph({ container: 'container', width, height, modes: { default: ['drag-canvas', 'drag-node'], }, layout: { type: 'fruchterman', gravity: 5, speed: 5, }, animate: true, defaultNode: { size: 30, style: { lineWidth: 2, stroke: '#5B8FF9', fill: '#C6E5FF', }, }, defaultEdge: { size: 2, color: '#e2e2e2', style: { endArrow: { path: 'M 0,0 L 8,4 L 8,-4 Z', fill: '#e2e2e2', }, }, }, }); // 以下是重点 graph.node(node => { if (node.flag === 'b') { return { style:{ fill: '#fff', stroke: '#ea7171' } } } return { style: { fill: '#2db7f5', stroke: '#ea7171' } } }); graph.data(data); graph.render(); 

 /*******下面是具体的Graphin的判断*********/

data.nodes.forEach(node => {
    if (node.flag === 'b') {
        node.style = {
          ...node.style,
          keyshape:{
            fill: '#eb6bbf',
            size: 50,
            stroke: '#eb6bbf',
          },
          halo: {
            fill: '#ff66cc',
            size: 100,
            stroke: '#ff66cc',
            opacity: .4,
            lineWidth: 2
          }
          }
      } else {
        node.style = {
          ...node.style,
          keyshape:{
            fill: '#ff9948',
            size: 40,
            stroke: '#ff9948',
          },
          halo: {
            fill: '#ff9948',
            size: 60,
            stroke: '#ff9948',
            opacity: .4,
            lineWidth: 2
          }
      }
      }
      // node.style = {
      //   ...node.style,
      //   // icon: {
      //   //   type: 'font',
      //   //   fontFamily: 'graphin',
      //   //   // value: icons.user,
      //   // },
      // };
  node.status = {
    selected: true
  }
});


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM