创建节点
选项
节点都有共同的基类 Cell,除了从 Cell 继承的选项外,还支持以下选项。
属性名 | 类型 | 默认值 | 描述 |
---|---|---|---|
x | Number | 0 | 节点位置 x 坐标,单位为 ‘px’ |
y | Number | 0 | 节点位置 y 坐标,单位为 ‘px’ |
width | Number | 1 | 节点宽度,单位为 ‘px’ |
height | Number | 1 | 节点高度,单位为 ‘px’ |
angle | Number | 0 | 节点旋转角度 |
方式一:构造函数
import { Shape } from '@antv/x6'
// 创建节点
const rect = new Shape.Rect({
x: 100,
y: 200,
width: 80,
height: 40,
angle: 30,// 节点的旋转角度
attrs: {
body: {
fill: 'blue',
},
label: {
text: 'Hello',
fill: 'white',
},
},
})
// 添加到画布
graph.addNode(rect)
也可以先创建节点,然后调用节点提供的方法来设置节点的大小、位置、旋转角度、样式等。
const rect = new Shape.Rect()
rect
// 设置节点位置
.position(100, 200)
// 设置节点大小
.resize(80, 40)
// 旋转节点
.rotate(30)
// 设置节点样式
.attr({
body: {
fill: 'blue',
},
label: {
text: 'Hello',
fill: 'white',
},
})
// 添加到画布
graph.addNode(rect)
方式二:graph.addNode()
还可以使用 graph.addNode 方法来创建节点并添加节点到画布,推荐大家使用这个便利的方法。
const rect = graph.addNode({
shape: 'rect', // 指定使用何种图形,默认值为 'rect'
x: 100,
y: 200,
width: 80,
height: 40,
angle: 30,
attrs: {
body: {
fill: 'blue',
},
label: {
text: 'Hello',
fill: 'white',
},
},
})
定制样式Attrs
例如 Shape.Rect 节点定义了 ‘body’(代表
const rect = new Shape.Rect({
x: 100,
y: 40,
width: 100,
height: 40,
attrs: {
body: {
fill: '#2ECC71', // 背景颜色
stroke: '#000', // 边框颜色
},
label: {
text: 'rect', // 文本
fill: '#333', // 文字颜色
fontSize: 13, // 文字大小
},
},
})