X6
X6 copied to clipboard
自定义polygon节点(菱形的),如何设置width/height,让里面的文本不超出节点边框
问题描述
项目中的判断节点是用的自定义polygon,它有2行文本,这2行文本的内容都是动态的,可能是第1行更长,也可能是第2行更长,请问有什么办法可以根据2行文本的最大长度来计算自定义polygon节点的width/height,使得文本不会超出节点的边框
重现链接
https://x6.antv.vision/zh/examples/node/custom-node#custom-with-svg
重现步骤
我用的是x6官网图表示例里的自定义节点 代码如下:
import { Graph } from '@antv/x6'
function calc(str) {
const chineseCount = str.match(/[\u4e00-\u9fa5]/g) ? str.match(/[\u4e00-\u9fa5]/g).length : 0
const englishCount = str.match(/[a-zA-Z]/g) ? str.match(/[a-zA-Z]/g).length : 0
const spaceCount = str.match(/\s/g) ? str.match(/\s/g).length : 0
const digitCount = str.match(/\d/g) ? str.match(/\d/g).length : 0
const punctuationCount = str.match(/[^\u4e00-\u9fa5a-zA-Z\s\d]/g) ? str.match(/[^\u4e00-\u9fa5a-zA-Z\s\d]/g).length : 0
let sum = chineseCount * 12 + englishCount * 8 + spaceCount * 2 + digitCount * 7 + punctuationCount * 3 + extra
if (chineseCount) {
sum += Math.floor((chineseCount / 2) * 12)
}
return sum
}
Graph.registerNode(
'custom-rect',
{
width: 200,
height: 40,
attrs: {
body: {
stroke: '#DA75FD',
strokeWidth: 1,
fill: '#FBE8FE',
rx: 6,
ry: 6,
refWidth: 1,
refHeight: 1,
},
label1: {
refX: 0.5,
refY: 0.5,
refY2: -16,
fill: '#000',
fontSize: 12,
textAnchor: 'middle',
textVerticalAnchor: 'top'
},
label2: {
refX: 0.5,
refY: 0.5,
refY2: 16,
fontSize: 12,
fill: '#000',
textAnchor: 'middle',
textVerticalAnchor: 'bottom'
},
},
markup: [
{
tagName: 'rect',
selector: 'body',
},
{
tagName: 'text',
selector: 'label1',
},
{
tagName: 'text',
selector: 'label2',
},
],
},
true,
)
Graph.registerNode(
'custom-polygon',
{
width: 200,
height: 60,
attrs: {
body: {
strokeWidth: 1,
refWidth: 1,
refHeight: 1,
stroke: '#6E63E6',
fill: '#EAE8FF',
refPoints: '0,10 10,0 20,10 10,20'
},
label1: {
refX: 0.5,
refY: 0.5,
refY2: -16,
fill: '#000',
fontSize: 12,
textAnchor: 'middle',
textVerticalAnchor: 'top'
},
label2: {
refX: 0.5,
refY: 0.5,
refY2: 16,
fontSize: 12,
fill: '#000',
textAnchor: 'middle',
textVerticalAnchor: 'bottom'
},
},
markup: [
{
tagName: 'polygon',
selector: 'body',
},
{
tagName: 'text',
selector: 'label1',
},
{
tagName: 'text',
selector: 'label2',
},
],
},
true,
)
const graph = new Graph({
container: document.getElementById('container')!,
grid: true,
})
graph.addNode({
x: 200,
y: 160,
shape: 'custom-rect',
attrs: {
label1: {
text: '测试文案测试文案测试文案'
},
label2: {
text: '1人 / 1次'
}
}
})
graph.addNode({
shape: 'custom-polygon',
x: 200,
y: 400,
label: 'polygon',
attrs: {
label1: {
text: '测试文案测试文案测试文案'
},
label2: {
text: '1人 / 1次'
}
}
})
预期行为
正确计算width/height,使得文字不要超出节点的边框
平台
- 操作系统: [Windows]
- 网页浏览器: [Google Chrome]
- X6 版本: [1.34.14]
屏幕截图或视频(可选)
No response
补充说明(可选)
自定义rect节点还可以计算下文本的长度,然后再给加点冗余空间,来不让文本超出,但是自定义polygon节点我实在想不出来应该如何计算,求大佬帮忙看看~
用html自定义节点,不要纠结用svg元素
我这边的场景是,这个棱形节点其实就是用来当作 IF 判断节点的,因此只在节点上显示了关键简要的信息。
提供另一个思路就是:对这个节点的文案或者其他标签不同颜色高亮显示,然后再实现一个 hover 后的悬浮提示组件,类似 Tooltip 的交互方式,如下图这样所示: