Skip to content
  1. Examples

Shape

This example shows how to use the shape attribute to change the shape of a node.

ts
import Ogma, { NodeShape } from '@linkurious/ogma';
import { GUI } from 'dat.gui';
import throttle from 'lodash/throttle';

const SHAPES: NodeShape[] = [
  'circle',
  'square',
  'cross',
  'diamond',
  'star',
  'equilateral',
  'triangle',
  'triangleDown',
  'triangleRight',
  'triangleLeft',
  'hexagon'
];

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

// Define the style of nodes. Use a deterministic function to randomly assign a shape to each node.
ogma.styles.addNodeRule({
  shape: n => SHAPES[+n.getId() % SHAPES.length]
});

// Generate a random graph
const graph = await ogma.generate.random({ nodes: 20, edges: 0 });
// Assign this graph to Ogma.
await ogma.setGraph(graph);
await ogma.layouts.grid({ locate: true, duration: 0 });
// Change the shape and color of a specific node
ogma.getNode('0')!.setAttributes({ color: 'orange', shape: 'triangleUp' });

const settings = {
  nodeCornerRadius: 0
};

const gui = new GUI();
gui
  .add(settings, 'nodeCornerRadius', 0, 0.2)
  .name('Node corner radius')
  .step(0.01)
  .onChange(
    throttle(() => {
      ogma.setOptions({
        nodeCornerRadius: settings.nodeCornerRadius
      });
    }, 100)
  );
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;
}