Skip to content
  1. Examples

Text

This example shows how to use the text attribute to display text on a node.

ts
import Ogma, { TextPosition } from '@linkurious/ogma';

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

const TEXT_POSITION: TextPosition[] = [
  'center',
  'left',
  'top',
  'right',
  'bottom'
];

// Add a rule to specify the text style.
// Here, the text to display (content property) is based on the id of the node.
ogma.styles.addNodeRule({
  text: {
    // random text positioning
    position: n => TEXT_POSITION[Number(n.getId()) % 4],
    maxLineLength: 140, // truncate
    size: 12,
    color: 'white',
    backgroundColor: '#444',
    minVisibleSize: 5,
    content: n => 'Node ' + n.getId()
  }
});

ogma.generate
  .random({ nodes: 15, edges: 0 })
  .then(graph => {
    ogma.setGraph(graph);
    ogma.view.locateGraph();

    ogma.getNode('0')!.setAttributes({
      text: { backgroundColor: '#d44', style: 'bold' }
    });
  })
  .then(() => ogma.layouts.grid());
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;
}