GoJS is a JavaScript library for implementing interactive diagrams. This page will show you the essentials of using GoJS.
Because GoJS is a JavaScript library that depends on HTML5 features, you will need to make sure that your page declares that it is an HTML5 document. And of course you need to load the library:
<!DOCTYPE html> <!-- 指定文档类型为 HTML5 --> <html> <head> <!-- 开发时请使用 go-debug.js,最终部署用 go.js --> <script src="go-debug.js"></script>
您可以到 下载页面 下载最新版 GoJS(包含所有例子),或者直接引用 CDN 文件:
<script src="https://unpkg.com/gojs/release/go-debug.js"></script>
每个 GoJS 图形实例都需要一个 HTML 容器 <div>
并明确指定其大小:
<!-- 图形的容器 div 需要明确指定大小,否则无法显示,本例子中我们还给该 DIV 添加了一个背景颜色,可以很方便的查看其大小。 --> <div id="myDiagramDiv" style="width:400px; height:150px; background-color: #DAE4E4;"></div>
在 JS 代码中,需要将 <div>
的 id
作为参数来创建图形。
var $ = go.GraphObject.make; var myDiagram = $(go.Diagram, "myDiagramDiv");
以上的代码最终结果是创建了一个空的图形,效果如下:
Notice that go
is the "namespace" in which all GoJS types reside. All code uses of GoJS classes such as Diagram or Node or Panel or Shape or TextBlock will be prefixed with "go.
".
This article will show you by example how to use go.GraphObject.make
to build GoJS objects. For more detail, read Building Objects in GoJS. Using $
as an abbreviation for go.GraphObject.make
is so handy that we will assume its use from now on. If you use $
for something else in your code, you can always pick a different short variable name, such as $$
or MAKE
or GO
.
The Nodes and Links of a Diagram are visualizations of data that is managed by a Model. GoJS has a model-view architecture, where Models hold the data (arrays of JavaScript objects) that describe nodes and links, and Diagrams act as views to visualize this data using actual Node and Link objects. Models, not Diagrams, are what you load and then save after editing. You add whatever properties you need for your app on the data objects in the model; you do not add properties to or modify the prototype of the Diagram and GraphObject classes.
Here's an example of a Model and Diagram, followed by the actual diagram it generates:
var $ = go.GraphObject.make; var myDiagram = $(go.Diagram, "myDiagramDiv", { "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo });var myModel = $(go.Model); // in the model data, each node is represented by a JavaScript object: myModel.nodeDataArray = [ { key: "Alpha" }, { key: "Beta" }, { key: "Gamma" } ]; myDiagram.model = myModel;
The diagram displays the three nodes that are in the model. Some interaction is already possible:
Nodes are styled by creating templates consisting of GraphObjects and setting properties on those objects. To create a Node, we have several building block classes at our disposal:
All of these building blocks are derived from the GraphObject abstract class, so we casually refer to them as GraphObjects or objects or elements. Note that a GraphObject is not an HTML DOM element, so there is not as much overhead in creating or modifying such objects.
We want the model data properties to affect our Nodes, and this is done by way of data bindings. Data bindings allow us to change the appearance and behavior of GraphObjects in Nodes by automatically setting properties on those GraphObjects to values that are taken from the model data. The model data objects are plain JavaScript objects. You can choose to use whatever property names you like on the node data in the model.
The default Node template is simple: A Node which contains one TextBlock. There is a data binding between a TextBlock's text
property and the model data's key
property. In code, the template looks something like this:
myDiagram.nodeTemplate = $(go.Node, $(go.TextBlock, // TextBlock.text is bound to Node.data.key new go.Binding("text", "key")) );
TextBlocks, Shapes, and Pictures are the primitive building blocks of GoJS. TextBlocks cannot contain images; Shapes cannot contain text. If you want your node to show some text, you must use a TextBlock. If you want to draw or fill some geometrical figures, you must use a Shape.
More generally, the skeleton of a Node template will look something like this:
myDiagram.nodeTemplate = $(go.Node, "Vertical", // second argument of a Node/Panel can be a Panel type /* set Node properties here */ { // the Node.location point will be at the center of each node locationSpot: go.Spot.Center }, /* add Bindings here */ // example Node binding sets Node.location to the value of Node.data.loc new go.Binding("location", "loc"), /* add GraphObjects contained within the Node */ // this Shape will be vertically above the TextBlock $(go.Shape, "RoundedRectangle", // string argument can name a predefined figure { /* set Shape properties here */ }, // example Shape binding sets Shape.figure to the value of Node.data.fig 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")) );
The nesting of GraphObjects within Panels can be arbitrarily deep, and every class has its own unique set of properties to explore, but this shows the general idea.
Now that we have seen how to make a Node template, let's see a live example. We will make a simple template commonly seen in organizational diagrams — an image next to a name. Consider the following Node template:
var $ = go.GraphObject.make; var myDiagram = $(go.Diagram, "myDiagramDiv", { "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo }); // define a simple Node template myDiagram.nodeTemplate = $(go.Node, "Horizontal", // the entire node will have a light-blue background { background: "#44CCFF" }, $(go.Picture, // Pictures should normally have an explicit width and height. // This picture has a red background, only visible when there is no source set // or when the image is partially transparent. { margin: 10, width: 50, height: 50, background: "red" }, // Picture.source is data bound to the "source" attribute of the model data new go.Binding("source")), $(go.TextBlock, "Default Text", // the initial value for TextBlock.text // some room around the text, a larger font, and a white stroke: { margin: 12, stroke: "white", font: "bold 16px sans-serif" }, // TextBlock.text is data bound to the "name" attribute of the model data new go.Binding("text", "name")) ); var model = $(go.Model); model.nodeDataArray = [ // note that each node data object holds whatever properties it needs; // for this app we add the "name" and "source" properties { name: "Don Meow", source: "/images/learn/cat1.png" }, { name: "Copricat", source: "/images/learn/cat2.png" }, { name: "Demeter", source: "/images/learn/cat3.png" }, { /* Empty node data */ } ]; myDiagram.model = model;
That code produces this diagram:
We may want to show some "default" state when not all information is present, for instance when an image does not load or when a name is not known. The "empty" node data in this example is used to show that node templates can work perfectly well without any of the properties on the bound data.
With a custom node template our diagram is becoming a pretty sight, but perhaps we want to show more. Perhaps we want an organizational chart to show that Don Meow is really the boss of a cat cartel. So we will create a complete organization chart diagram by adding some Links to show the relationship between individual nodes and a Layout to automatically position the nodes.
In order to get links into our diagram, the basic Model
is not going to cut it. We are going to have to pick one of the other two models in GoJS, both of which support Links. These are GraphLinksModel
and TreeModel
. (Read more about models here.)
In GraphLinksModel, we have model.linkDataArray
in addition to the model.nodeDataArray
. It holds an array of JavaScript objects, each describing a link by specifying the "to" and "from" node keys. Here's an example where node A links to node B and where node B links to node C:
var model = $(go.GraphLinksModel); model.nodeDataArray = [ { key: "A" }, { key: "B" }, { key: "C" } ]; model.linkDataArray = [ { from: "A", to: "B" }, { from: "B", to: "C" } ]; myDiagram.model = model;
A GraphLinksModel allows you to have any number of links between nodes, going in any direction. There could be ten links running from A to B, and three more running the opposite way, from B to A.
A TreeModel works a little differently. Instead of maintaining a separate array of link data, the links in a tree model are created by specifying a "parent" for a node data. Links are then created from this association. Here's the same example done as a TreeModel, with node A linking to node B and node B linking to node C:
var model = $(go.TreeModel); model.nodeDataArray = [ { key: "A" }, { key: "B", parent: "A" }, { key: "C", parent: "B" } ]; myDiagram.model = model;
TreeModel is simpler than GraphLinksModel, but it cannot make arbitrary link relationships, such as multiple links between the same two nodes, or having multiple parents. Our organizational diagram is a simple hierarchical tree-like structure, so we will choose TreeModel for this example.
First, we will complete the data by adding a few more nodes, using a TreeModel, and specifying keys and parents in the data.
var $ = go.GraphObject.make; var myDiagram = $(go.Diagram, "myDiagramDiv", { "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo }); // the template we defined earlier myDiagram.nodeTemplate = $(go.Node, "Horizontal", { background: "#44CCFF" }, $(go.Picture, { margin: 10, width: 50, height: 50, background: "red" }, new go.Binding("source")), $(go.TextBlock, "Default Text", { margin: 12, stroke: "white", font: "bold 16px sans-serif" }, new go.Binding("text", "name")) ); var model = $(go.TreeModel); model.nodeDataArray = [ // the "key" and "parent" property names are required, // but you can add whatever data properties you need for your app { key: "1", name: "Don Meow", source: "/images/learn/cat1.png" }, { key: "2", parent: "1", name: "Demeter", source: "/images/learn/cat2.png" }, { key: "3", parent: "1", name: "Copricat", source: "/images/learn/cat3.png" }, { key: "4", parent: "3", name: "Jellylorum", source: "/images/learn/cat4.png" }, { key: "5", parent: "3", name: "Alonzo", source: "/images/learn/cat5.png" }, { key: "6", parent: "2", name: "Munkustrap", source: "/images/learn/cat6.png" } ]; myDiagram.model = model;
As you can see the TreeModel automatically creates the necessary Links to associate the Nodes, but it's hard to tell whose parent is who.
Diagrams have a default layout which takes all nodes that do not have a location and gives them locations, arranging them in a grid. We could explicitly give each of our nodes a location to sort out this organizational mess, but as an easier solution in our case, we will use a layout that gives us good locations automatically.
We want to show a hierarchy, and are already using a TreeModel, so the most natural layout choice is TreeLayout. TreeLayout defaults to flowing from left to right, so to get it to flow from top to bottom (as is common in organizational diagrams), we will set the angle
property to 90.
Using layouts in GoJS is usually simple. Each kind of layout has a number of properties that affect the results. There are samples for each layout (like TreeLayout Demo) that showcase its properties.
// define a TreeLayout that flows from top to bottom myDiagram.layout = $(go.TreeLayout, { angle: 90, layerSpacing: 35 });
GoJS has several other layouts, which you can read about here.
Adding the layout to the diagram and model so far, we can see our results:
var $ = go.GraphObject.make; var myDiagram = $(go.Diagram, "myDiagramDiv", { "undoManager.isEnabled": true, // enable Ctrl-Z to undo and Ctrl-Y to redo layout: $(go.TreeLayout, // specify a Diagram.layout that arranges trees { angle: 90, layerSpacing: 35 }) }); // the template we defined earlier myDiagram.nodeTemplate = $(go.Node, "Horizontal", { background: "#44CCFF" }, $(go.Picture, { margin: 10, width: 50, height: 50, background: "red" }, new go.Binding("source")), $(go.TextBlock, "Default Text", { margin: 12, stroke: "white", font: "bold 16px sans-serif" }, new go.Binding("text", "name")) ); var model = $(go.TreeModel); model.nodeDataArray = [ { key: "1", name: "Don Meow", source: "/images/learn/cat1.png" }, { key: "2", parent: "1", name: "Demeter", source: "/images/learn/cat2.png" }, { key: "3", parent: "1", name: "Copricat", source: "/images/learn/cat3.png" }, { key: "4", parent: "3", name: "Jellylorum", source: "/images/learn/cat4.png" }, { key: "5", parent: "3", name: "Alonzo", source: "/images/learn/cat5.png" }, { key: "6", parent: "2", name: "Munkustrap", source: "/images/learn/cat6.png" } ]; myDiagram.model = model;
Our diagram is starting to look like a proper organization chart, but we could do better with the links.
We will construct a new Link template that will better suit our wide, boxy nodes. A Link is a different kind of Part, not like a Node. The main element of a Link is the Link's shape, and must be a Shape that will have its geometry computed dynamically by GoJS. Our link is going to consist of just this shape, with its stroke a little thicker than normal and dark gray instead of black. Unlike the default link template we will not have an arrowhead. And we will change the Link routing
property from Normal to Orthogonal, and give it a corner
value so that right-angle turns are rounded.
// 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 } );
Combining our Link template with our Node template, TreeModel, and TreeLayout, we finally have a full organization diagram. The complete code is repeated below, and the resulting diagram follows:
var $ = go.GraphObject.make; var myDiagram = $(go.Diagram, "myDiagramDiv", { "undoManager.isEnabled": true, // enable Ctrl-Z to undo and Ctrl-Y to redo layout: $(go.TreeLayout, // specify a Diagram.layout that arranges trees { angle: 90, layerSpacing: 35 }) }); // the template we defined earlier myDiagram.nodeTemplate = $(go.Node, "Horizontal", { background: "#44CCFF" }, $(go.Picture, { margin: 10, width: 50, height: 50, background: "red" }, new go.Binding("source")), $(go.TextBlock, "Default Text", { margin: 12, stroke: "white", font: "bold 16px sans-serif" }, new go.Binding("text", "name")) ); // define a Link template that routes orthogonally, with no arrowhead myDiagram.linkTemplate = $(go.Link, { routing: go.Link.Orthogonal, corner: 5 }, $(go.Shape, { strokeWidth: 3, stroke: "#555" })); // the link shape var model = $(go.TreeModel); model.nodeDataArray = [ { key: "1", name: "Don Meow", source: "/images/learn/cat1.png" }, { key: "2", parent: "1", name: "Demeter", source: "/images/learn/cat2.png" }, { key: "3", parent: "1", name: "Copricat", source: "/images/learn/cat3.png" }, { key: "4", parent: "3", name: "Jellylorum", source: "/images/learn/cat4.png" }, { key: "5", parent: "3", name: "Alonzo", source: "/images/learn/cat5.png" }, { key: "6", parent: "2", name: "Munkustrap", source: "/images/learn/cat6.png" } ]; myDiagram.model = model;
You may want to read more tutorials, such as the GraphObject manipulation tutorial. You can also watch tutorials on YouTube.
Also consider perusing the samples to see some of the diagrams possible with GoJS, or read the technical introduction to get an in-depth look at the components of GoJS.