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 }
);