Skip to content
  1. Examples

Connect nodes

This example shows how to let the user create edges. It uses the connectNodes tool.
To create an edge, press "ctrl", click on a node and drag the cursor to annother node.).

ts
import Ogma from '@linkurious/ogma';

const ogma = new Ogma({
  container: 'graph-container'
});

ogma.events.on('dragStart', () => {
  console.log('dragStart', ogma.keyboard.isKeyPressed('ctrl'));
  ogma.tools.connectNodes.enable({
    strokeColor: 'red',

    createNode: n => {
      n.attributes = { ...n.attributes, color: 'orange' };
      return n;
    },

    createEdge: e => {
      e.attributes = { ...e.attributes, color: 'orange' };
      return e;
    },
    onComplete: (source, target, edge) => {
      console.log(
        'source:',
        source.getId(),
        ', target: ',
        target.getId(),
        ', edge id: ',
        edge!.getId()
      );
    }
  });
});

ogma.generate
  .random({ nodes: 16, edges: 5 })
  .then(graph => ogma.setGraph(graph))
  .then(() => ogma.layouts.grid({ locate: true }));
html
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />

    <link type="text/css" rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div id="graph-container"></div>
    <script type="module" src="index.ts"></script>
  </body>
</html>
css
#graph-container {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
  margin: 0;
  overflow: hidden;
}
#control {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
}
#control label {
  display: block;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}