JointJS - define 函数和 calc 相对计算函数
define 函数
file:[define 函数的定义]
Element.define(type [, defaultInstanceProperties, prototypeProperties, staticProperties])
参数名 | 描述 |
---|---|
defaultInstanceProperties | 覆盖默认的属性。JointJS 渲染的结果是 SVG,所以属性设置可以参考 MDN。 |
prototypeProperties | 图形的子图形(子元素)的 SVG 标签类型。比如,Rectangle 图形下有 RectSVGElement 和 TextSVGElement 两个子图形(子元素) |
子图形需要 markup 这一个配置项,否则 Paper 不显示图形。下面是一个 define 函数定义图形的基本示例:
joint.dia.Element.define(
"standard.Rectangle",
{
attrs: {
// 我们定义的 markup 中第一个对象 selector 同样也对应这里的 key。
// body: {
main: {
width: "calc(w)",
height: "calc(h)",
strokeWidth: 2,
stroke: "#000000",
fill: "#FFFFFF"
},
label: {
textVerticalAnchor: "middle",
textAnchor: "middle",
x: "calc(0.5*w)",
y: "calc(0.5*h)",
fontSize: 12,
fill: "#333333"
}
}
},
{
markup: [
// 这个图形中有一个子元素 RectSVGELement,因此 tagName: "rect"。而 selector 的意思是在定义的图形中,当
// 对的 RectSVGELement 设置自定义 attrs 时 rect.attr({body: {}}) 中这个 key 里面的属性会应用到
// RectSVGELement 中。
{
tagName: "rect",
// selector: "body"
selector: "main"
},
{
tagName: "text",
selector: "label"
}
]
}
);
其中有两个最重要的 attrs 和 markup。
- markup 是用来指定一个图形下的子元素(子图形)的 SVG 的类型,比如:SVGRectElement。
- attrs 是给子图形定义样式的配置属性,markup 中的 selector 的值就是子图形使用的样式名称,类似于给 HTML5 的一个标签添加 id,通过 id 写 CSS 样式。
attrs 符合 SVG 的属性,查阅 MDN 文档,对这些 SVG 标签进行设置,比如宽度、高度、x、y 等。
calc
JointJS 中的 calc
根据图形的宽度和高度进行计算,例如:calc(w)
计算得到图形的宽度;calc(w*0.5)
计算得到图形的一半宽度。
一个图形最外层是一个 g 标签,我们可以理解为这个图形的盒子。rect.resize(150, 50)
意思是给图形的盒子设置宽度和高度,因此,calc(w)
得到的结果就是 150。
示例
const namespace = joint.shapes;
const graph = new joint.dia.Graph({}, { cellNamespace: namespace });
const paper = new joint.dia.Paper({
el: document.getElementById("paper-custom-elements"),
model: graph,
width: 1000,
height: 400,
gridSize: 10,
drawGrid: true,
background: {
color: "rgba(0, 255, 0, 0.3)"
},
cellViewNamespace: namespace
});
joint.dia.Element.define(
"standard.Rectangle",
{
attrs: {
// 我们定义的 markup 中第一个对象 selector 同样也对应这里的 key。
// body: {
main: {
width: "calc(w)",
height: "calc(h)",
strokeWidth: 2,
stroke: "#000000",
fill: "#FFFFFF"
},
label: {
textVerticalAnchor: "middle",
textAnchor: "middle",
x: "calc(0.5*w)",
y: "calc(0.5*h)",
fontSize: 12,
fill: "#333333"
}
}
},
{
markup: [
// 这个图形中有一个子元素 RectSVGELement,因此 tagName: "rect"。而 selector 的意思是在定义的图形中,当
// 对的 RectSVGELement 设置自定义 attrs 时 rect.attr({body: {}}) 中这个 key 里面的属性会应用到
// RectSVGELement 中。
{
tagName: "rect",
// selector: "body"
selector: "main"
},
{
tagName: "text",
selector: "label"
}
]
}
);
const rect = new joint.shapes.standard.Rectangle();
rect.position(50, 50);
rect.resize(150, 50);
rect.attr({
main: {
rx: 10
},
label: {
text: "Hello World!"
}
});
graph.addCells(rect);