Skip to content
  1. Examples

Zoom-dependent texts

This example shows how to update the edge labels on zoom. It uses the viewChanged event to update the edge labels' size and content.

ts
import Ogma from '@linkurious/ogma';

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

let maxLineLength = 30;
const longLabelText =
  'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ornare lectus ac ligula vestibulum molestie.';
const targetZoom = 5;
const textRule = ogma.styles.addRule({
  edgeAttributes: {
    text: {
      backgroundColor: '#222',
      color: 'white',
      content: () => {
        const str = longLabelText.substring(0, maxLineLength);
        const suffix = maxLineLength < longLabelText.length ? '...' : '';
        return `${str}${suffix}`;
      },
      maxLineLength: 18,
      adjustAngle: false,
      minVisibleSize: 0
    }
  }
});

// update node visibility based on zoom level and view position
ogma.events.on('viewChanged', () => {
  const zoom = ogma.view.getZoom();
  const ratio = 1 - Math.max(0, Math.min(1, (targetZoom - zoom) / targetZoom));
  maxLineLength = longLabelText.length * ratio;
  // refresh the rule and load icons
  textRule.refresh();
});

const graph = await ogma.generate.flower({ nodes: 20 });
await ogma.setGraph(graph);
await ogma.layouts.force({ steps: 100, theta: 0.99, 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;
}