Skip to content
  1. Examples

Container resizing

This example shows how to use the setSize method to resize the container of the view on the fly.

ts
import Ogma from '@linkurious/ogma';

const ogma = new Ogma({
  container: 'graph-container',
  options: {
    backgroundColor: 'white'
  }
});
ogma.view
  .setSize({ width: 400, height: 400 })
  .then(() => ogma.generate.random({ nodes: 5, edges: 10 }))
  .then(g => ogma.setGraph(g))
  .then(() => ogma.view.locateGraph());

[
  ['left', 'top'],
  ['right', 'top'],
  ['right', 'bottom'],
  ['left', 'bottom']
].forEach(classes => {
  let dragging = false;
  let startPoint = [0, 0];
  let size = { width: 0, height: 0 };
  let wFactor = 2;
  let hFactor = 2;

  const handle = document.createElement('div');
  classes.forEach(c => {
    handle.classList.add(c);
    if (c === 'left') wFactor = -2;
    if (c === 'top') hFactor = -2;
  });
  handle.classList.add('handle');

  handle.addEventListener('mousedown', evt => {
    evt.preventDefault();
    evt.stopPropagation();

    dragging = true;
    size = ogma.view.getSize();
    startPoint = [evt.clientX, evt.clientY];
  });
  document.addEventListener('mouseup', () => {
    dragging = false;
    //ogma.view.forceResize();
  });
  document.addEventListener('mousemove', evt => {
    if (!dragging) return;
    const dx = evt.clientX - startPoint[0];
    const dy = evt.clientY - startPoint[1];

    const width = Math.max(300, size.width + wFactor * dx);
    const height = Math.max(300, size.height + hFactor * dy);
    ogma.view.setSize({ width, height });
  });
  ogma.layers.addLayer(handle);
  ogma.view.afterNextFrame().then(() => {
    handle.style.left = 'unset';
    handle.style.top = 'unset';
  });
});
html
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <!---->

    <link type="text/css" rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="container">
      <div id="graph-container"></div>
    </div>
    <script type="module" src="index.ts"></script>
  </body>
</html>
css
.container{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}
body{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #dedede;
}
#graph-container{
  border: 1px dashed black;
}
.handle{
  background-color: #38e;
  padding: 4px;
  width: 0;
  height: 0;
  cursor: move;
}
.handle.left{
  left: 0;
}
.handle.top{
  top: 0;
}
.handle.right{
  right: 0;
}
.handle.bottom{
  bottom: 0;
}
.handle:hover{
  padding: 6px;
}