Gojs-起手式
本文主要概括了gojs入门需要了解的基本概念,以及它们间的关系
1.Diagrams and Models(图表与模型)
图表所包含的节点和连线是数据的可视化,这些数据是由模型管理的。Gojs是MV架构的,其中模型(M)保存着描述节点和连线的数据(数组和js对象),图表充当着视图(V)的角色,视图是由真实的节点和连线组成的。
2.Node(节点)
节点可以由模板创建出来,模板是由GraphObjects组成的,用户可以在这些对象上设置自定义属性。Gojs由集中预设的模型:
- Shape, 用颜色来展示预定义或者自定义的图形
- TextBlock,文本块,用来展示或者编辑文本
- Picture,用来展示图片
- Panel,容纳多个别的GraphObjects的容器,panel的位置和大小形状由panel的类型决定
所有的这些块都由 GraphObject抽象类衍生而来。注意:GraphObject对象并不是一个DOM元素,所以创建和修改GraphObject并没有那么多的开销。
通过数据绑定可以改变GraphObject的外观和行为,模型的数据是普通的js对象。默认的Node模板是一个TextBlock。
myDiagram.nodeTemplate =
$(go.Node,
$(go.TextBlock,
//绑定(映射)节点数据中key属性到TextBlock的text属性上
new go.Binding("text", "key"))
);
TextBlocks, Shapes, Pictures 是Gojs中原始的块单位(最小的,它们不能再作为其他block的容器),TextBlock不可以包含图片,Shape不可以包含文本,
3.Node模板的结构
myDiagram.nodeTemplate =
$(go.Node, "Vertical", // Vertical: 一个节点中 所有元素的布局方式未纵向排列
/* 设置Node的属性:位置、背景色等 */
{ // the Node.location point will be at the center of each node
locationSpot: go.Spot.Center
},
/* 映射Node属性和外部数据属性 */
// example Node binding sets Node.location to the value of Node.data.loc
new go.Binding("location", "loc"),
/* Node节点所包含的GraphObject 基本元素或者组合元素 */
// this Shape will be vertically above the TextBlock
$(go.Shape,
/*设置Shape的属性 */
"RoundedRectangle", // string argument can name a predefined figure
{ /* set Shape properties here */ },
//映射属性到数据 非必须
new go.Binding("figure", "fig")),
$(go.TextBlock,
"default text", // string argument can be initial text string
{ /* set TextBlock properties here */ },
// example TextBlock binding sets TextBlock.text to the value of Node.data.key
new go.Binding("text", "key"))
);
4.定义Model
节点数据数组即为要组织的数据,连线数据数组定义数据间的相互关系
连线模型定义了数据和数据间的连线关系
var model = $(go.GraphLinksModel);
/*数据数组*/
model.nodeDataArray =
[
{ key: "A" },
{ key: "B" },
{ key: "C" }
];
/*连线数据数组*/
model.linkDataArray =
[
{ from: "A", to: "B" },//连线由A指向B 属性from和to是必须的
{ from: "B", to: "C" }
];
myDiagram.model = model;
// A--->B--->C
树状模型是一种特殊的连线模型,有特定的层级意义
var model = $(go.TreeModel);
model.nodeDataArray =
[
{ key: "A" },
{ key: "B", parent: "A" },// 属性 "key" 和 "parent" 是必须的
{ key: "C", parent: "B" }
];
myDiagram.model = model;
// A--->B--->C
5.连线模型
不设置连线模型时,图表元素之间的连线有默认的样式,通过设置连线模型可以自定义连线的样式:宽度、颜色、形状、注记等.
link中最主要的元素是它的形状,并且必须是Shape类型的
// define a Link template that routes orthogonally, with no arrowhead
myDiagram.linkTemplate =
$(go.Link,
// default routing is go.Link.Normal
// default corner is 0
{ routing: go.Link.Orthogonal, corner: 5 },
$(go.Shape, { strokeWidth: 3, stroke: "#555" }) // the link shape
// if we wanted an arrowhead we would also add another Shape with toArrow defined:
// $(go.Shape, { toArrow: "Standard", stroke: null }
);