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