自定义主题
上一篇
主题总览
下一篇
色板
Loading...
除了使用内置主题外,G6 还支持创建自定义主题来满足特定的视觉需求。本文将介绍如何创建和使用自定义主题。
一个自定义主题需要遵循主题的基本结构,包含画布背景色和元素样式配置:
const customTheme = {// 1. 画布背景色background: '#f0f0f0',// 2. 节点配置node: {// 调色板配置palette: {type: 'group',color: ['#1783FF', '#00C9C9' /* 自定义颜色... */],},// 基础样式style: {fill: '#fff',stroke: '#d9d9d9',lineWidth: 1,// ... 其他节点样式},// 状态样式state: {selected: {fill: '#e8f3ff',stroke: '#1783FF',},// ... 其他状态样式},},// 3. 边配置edge: {style: {stroke: '#d9d9d9',lineWidth: 1,// ... 其他边样式},state: {// ... 状态样式},},// 4. Combo 配置combo: {style: {fill: '#f7f7f7',stroke: '#d9d9d9',// ... 其他 Combo 样式},state: {// ... 状态样式},},};
在创建自定义主题时,需要注意以下限制:
仅支持静态值
// ❌ 错误示例:不支持回调函数const theme = {node: {style: {fill: (d) => d.style.color,},},};
不支持配置元素类型
// ❌ 错误示例:不支持在主题中配置元素类型const theme = {node: {type: 'rect',style: {fill: '#fff',},},};
状态样式需要对应默认样式
// ✅ 正确示例:状态样式的属性在默认样式中都有定义const theme = {node: {style: {fill: '#fff',stroke: '#000',},state: {selected: {fill: '#e8f3ff',stroke: '#1783FF',},},},};
先注册主题,然后通过名称引用:
// 1. 注册主题import { register, ExtensionCategory } from '@antv/g6';register(ExtensionCategory.THEME, 'custom-theme', customTheme);// 2. 使用主题const graph = new Graph({theme: 'custom-theme',// ... 其他配置});