Ola Graph

A graph example for the library Ola

by Francisco Presencia Fandos

HTML

<script src="https://unpkg.com/smoothie@1.35.0/smoothie.js"></script>
<script src="https://cdn.jsdelivr.net/npm/ola@0/ola.min.js"></script>
<div class="legend">
  <span class="dot control">Real value</span>
  <span class="dot interpolated">Interpolated</span>
</div>

<div class="container">
  <canvas id="graph" height="400"></canvas>
</div>

CSS

body {
  margin: 0;
  padding: 0;
  font-family: Sans-Serif;
}

.legend {
  margin: 10px;
}

.dot {
  margin-right: 10px;
}

.dot::before {
  content: '';
  width: 15px;
  height: 15px;
  margin-bottom: -2px;
  margin-right: 5px;
  border-radius: 10px;
  display: inline-block;
  background: red;
}

.dot.control::before {
  background: rgba(0, 0, 255, 0.4);
}

.dot.interpolated::before {
  background: rgba(255, 0, 0, 0.6);
}

.container {
  position: relative;
  margin: 10px;
  box-shadow: 0 0 0 1px #ccc;
  border-radius: 8px;
  height: 200px;
  overflow: hidden;
}

canvas {
  transform: scale(0.5);
  transform-origin: top left;
}

JavaScript

// Initial value for the position; center of the container
const angle = Ola(0, 1000);

// Double size and scale for better resolution
const canvas = document.querySelector("#graph");
canvas.width = window.innerWidth * 2;

const graph = new SmoothieChart({
  grid: { strokeStyle: '#fff', fillStyle: '#fff' },
  maxValue: 1,
  minValue: 0,
  // This makes it render a bit worse, but otherwise it's cheating
  interpolation: 'step'
});
graph.streamTo(canvas, 1200);

const control = new TimeSeries();
const output = new TimeSeries();

// Add to SmoothieChart
graph.addTimeSeries(control, { strokeStyle: 'rgba(0, 0, 255, 0.3)' });
graph.addTimeSeries(output, { strokeStyle: 'rgba(255, 0, 0, 0.6)', lineWidth: 2 });
control.append(new Date(), 0);

(function tick() {
  output.append(new Date(), angle.value);
  requestAnimationFrame(tick);
})();

// Add a random value to each line every 1-2 seconds
(function update() {
  const to = Math.random();
  angle.value = to;
  control.append(new Date(), to);
  setTimeout(update, 1200);
})();