文本点点点实现思路:因为G6是canvas,所以可以通过创建一个canvas文本并获取其宽度,对比node最大宽度来判断是否显示点点点... 再循环文本判断获取到最大宽度的文本
`
getLableEllipsis(text, maxWidth, context) {
let width = context.measureText(text).width
if (width <= maxWidth) {
return text
}
let ellipsis = '...'
let ellipsisWidth = context.measureText(ellipsis).width
let truncatedText = text
while (width + ellipsisWidth > maxWidth) {
truncatedText = truncatedText.slice(0, -1)
width = context.measureText(truncatedText).width
}
return truncatedText + ellipsis
},
async init() {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const fontSize = 14
context.font = `${fontSize}px Arial` // 根据你的实际字体样式进行设置
let that = this
G6.registerNode(
'icon-node',
{
options: {
size: [240, 80],
stroke: '#d0d9e3',
fill: '#f9fcfe'
},
draw(cfg, group) {
const styles = this.getShapeStyle(cfg)
const { labelCfg = {} } = cfg
const w = styles.width
const h = styles.height
const keyShape = group.addShape('rect', {
attrs: {
...styles,
x: -w / 2,
y: -h / 2,
radius: 5,
fill: '#f9fcfe',
stroke: '#d0d9e3'
}
})
if (cfg.label) {
let label = cfg?.label || '--'
const maxWidth = 200 //容器文本显示的最大宽度,超出用点点点...显示
const textWidth = context.measureText(cfg.label).width //通过canvas测量文本宽度,因为G6文本就是canvas
if (maxWidth < textWidth) {
label = that.getLableEllipsis(label, maxWidth, context)
}
group.addShape('text', {
attrs: {
...labelCfg.style,
x: 0, // 居中
y: -14,
textAlign: 'center',
textBaseline: 'middle',
text: label,
fill: '#000',
fontSize: fontSize
}
})
group.addShape('text', {
attrs: {
...labelCfg.style,
x: 0,
y: 14,
textAlign: 'center',
textBaseline: 'middle',
text: cfg?.accountId || '--',
fontSize: fontSize,
fill: '#000'
}
})
}
return keyShape
},
update: undefined
},
'rect'
)
}
canvas获取文本宽度 measureText
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const textWidth = context.measureText('文本文本文本文本').width