Ola Ball

An example of a ball approaching a dor for the library Ola

by Francisco Presencia Fandos

HTML

<script src="https://cdn.jsdelivr.net/npm/ola@0/ola.min.js"></script>
<div class="legend">
  <span class="dot control">Target position</span>
  <span class="dot interpolated">Interpolated</span>
</div>

<div id="pointer"></div>
<div id="ball"></div>

CSS

html,
body {
  display: block;
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  overflow: hidden;
  position: relative;
  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);
}

#pointer, #ball {
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 50%;
  width: 100px;
  height: 100px;
  margin: -50px;
}

#ball {
  background: rgba(255, 0, 0, 0.6);
}

#pointer {
  top: 25px;
  left: 25px;
  width: 50px;
  height: 50px;
  margin: -25px;
  background: rgba(0, 0, 255, 0.1);
}

JavaScript

// Meta -  Select the appropriate things
const pointer = document.querySelector('#pointer');
const ball = document.querySelector('#ball');

// Initial value for the position; center of the container
const pos = Ola({ x: 100, y: 100 });

// Read the position as fast as the CPU allows
(function tick() {
	ball.style.left = `${pos.x}px`;
	ball.style.top = `${pos.y}px`;
  requestAnimationFrame(tick);
})();

// Try swapping these two lines for click behavior:
//window.addEventListener('click', e => {
window.addEventListener('mousemove', e => {
	pos.set({ x: e.pageX, y: e.pageY });
	pointer.style.left = `${e.pageX}px`;
	pointer.style.top = `${e.pageY}px`;
});