Skip to content
  1. Examples

Hold space to drag

This example shows how to use the keydown event to enable dragging the viewport by holding the 'Space' key.

Hold 'Space' key to drag the viewport.

js
import Ogma, { Node } from '@linkurious/ogma';

const ogma = new Ogma({
  container: 'graph-container',
  options: {
    interactions: { pan: { enabled: false, cursor: 'grab' } }
  }
});

ogma.generate
  .random({ nodes: 300, edges: 200 })
  .then(graph => ogma.setGraph(graph))
  .then(() => ogma.layouts.force({ locate: true }));

/**
 * @param {boolean} enabled
 */
const setPanning = enabled =>
  ogma.setOptions({ interactions: { pan: { enabled } } });

ogma.events
  .on('keydown', evt => {
    if (evt.key === 'space') setPanning(true);
  })
  .on('keyup', evt => {
    if (evt.key === 'space') setPanning(false);
  });
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 src="index.js"></script>
  </body>
</html>
css
body,
html {
  width: 100%;
  height: 100%;
  text-align: center;
  margin: 0;
}

#graph-container {
  width: 100%;
  height: 100%;
  margin: auto;
  overflow: hidden;
  display: block;
  position: relative;
}