在AntV/G6图表库中,当节点的文字内容过长时,可以通过以下几种方式来优雅地显示省略号(...):
text 的 ellipsis 属性G6 提供了 text 配置项,可以通过设置 ellipsis 属性来在文字过长时显示省略号。
const graph = new G6.Graph({
container: 'mountNode',
width: 800,
height: 600,
defaultNode: {
type: 'circle',
labelCfg: {
style: {
fill: '#333',
fontSize: 14,
// 设置 ellipsis 属性
ellipsis: true,
// 设置最大宽度
maxWidth: 100,
},
},
},
});
// 添加节点
graph.data({
nodes: [
{
id: 'node1',
label: '这是一个非常长的节点名称,需要显示省略号',
x: 100,
y: 100,
},
],
});
graph.render();
label 的 formatter你可以通过自定义 label 的 formatter 函数来手动处理文字过长的情况。
const graph = new G6.Graph({
container: 'mountNode',
width: 800,
height: 600,
defaultNode: {
type: 'circle',
labelCfg: {
style: {
fill: '#333',
fontSize: 14,
},
// 自定义 formatter
formatter: (text) => {
const maxLength = 10; // 最大显示长度
return text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
},
},
},
});
// 添加节点
graph.data({
nodes: [
{
id: 'node1',
label: '这是一个非常长的节点名称,需要显示省略号',
x: 100,
y: 100,
},
],
});
graph.render();
textWrap 和 textMaxLine如果你希望文字在超出一定宽度时自动换行,并且只显示指定行数,可以使用 textWrap 和 textMaxLine 属性。
const graph = new G6.Graph({
container: 'mountNode',
width: 800,
height: 600,
defaultNode: {
type: 'circle',
labelCfg: {
style: {
fill: '#333',
fontSize: 14,
// 设置自动换行
textWrap: true,
// 设置最大行数
textMaxLine: 2,
// 设置最大宽度
maxWidth: 100,
},
},
},
});
// 添加节点
graph.data({
nodes: [
{
id: 'node1',
label: '这是一个非常长的节点名称,需要显示省略号',
x: 100,
y: 100,
},
],
});
graph.render();
tooltip 显示完整内容如果文字过长,可以在鼠标悬停时通过 tooltip 显示完整内容。
const graph = new G6.Graph({
container: 'mountNode',
width: 800,
height: 600,
defaultNode: {
type: 'circle',
labelCfg: {
style: {
fill: '#333',
fontSize: 14,
ellipsis: true,
maxWidth: 100,
},
},
},
modes: {
default: ['drag-node', 'zoom-canvas'],
// 启用 tooltip
tooltip: {
formatText(model) {
return model.label;
},
},
},
});
// 添加节点
graph.data({
nodes: [
{
id: 'node1',
label: '这是一个非常长的节点名称,需要显示省略号',
x: 100,
y: 100,
},
],
});
graph.render();
ellipsis 属性:简单直接,适合大多数场景。formatter:灵活控制,适合需要自定义逻辑的场景。textWrap 和 textMaxLine:适合需要多行显示的场景。tooltip:适合需要在悬停时显示完整内容的场景。根据你的具体需求选择合适的方式来实现节点文字的优雅显示。