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
}
});
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通