Nodejs 中使用 GoJS

As of 2.0, GoJS can be used in DOM-less contexts like Node.js. However there are some considerations:

For server-side operations that need to measure Pictures or TextBlocks, you should consider using a headless browser with Node. Click here for examples using Node with Puppeteer (headless Chrome).

Node.js example

If you saved the following JavaScript as nodescript.js and run it with node (node nodescript.js), it will output Model JSON results in the console, which include the locations of laid-out Nodes. You can use Node.js in this way to do server-side operations like large layouts, and then send the JSON to the client.

// This example loads the GoJS library, creates a Diagram with a layout and prints the JSON results,

// Reference GoJS. This assumes its in the same directory as this script:

var $ = go.GraphObject.make;  // for conciseness in defining templates

myDiagram = $(go.Diagram, '', // No DIV
            viewSize: new go.Size(400,400), // Set this property in DOM-less environments
            layout: $(go.LayeredDigraphLayout),
            'animationManager.isEnabled': false

// define a simple Node template
myDiagram.nodeTemplate =
  $(go.Node, 'Auto',
    new go.Binding('location', 'loc', go.Point.Parse).makeTwoWay(go.Point.Stringify),
    $(go.Shape, 'RoundedRectangle', { strokeWidth: 0},
      // Shape.fill is bound to
      new go.Binding('fill', 'color')),
      { margin: 8 },  // some room around the text
      // TextBlock.text is bound to
      new go.Binding('text', 'key'))

// After the layout, output results:
myDiagram.addDiagramListener('InitialLayoutCompleted', function() {

// load a model:
myDiagram.model = new go.GraphLinksModel(
  { key: 'Alpha', color: 'lightblue' },
  { key: 'Beta', color: 'orange' },
  { key: 'Gamma', color: 'lightgreen' },
  { key: 'Delta', color: 'pink' }
  { from: 'Alpha', to: 'Beta' },
  { from: 'Alpha', to: 'Gamma' },
  { from: 'Beta', to: 'Beta' },
  { from: 'Gamma', to: 'Delta' },
  { from: 'Delta', to: 'Alpha' }
加入 GoJS 交流群
GoJS 交流群 (769862113)