Cursor · 09 of 22

Glitch Cursor

Cursor distortion and offset

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="glitch-area" id="glitchArea">
  <h2>Glitch Zone</h2>
  <div class="glitch-dot" id="glitchDot"></div>
  <div class="glitch-ring" id="glitchRing"></div>
</div>

CSS

.glitch-area {
  position: relative;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #12121a;
  color: #f0f0f5;
  overflow: hidden;
  cursor: none;
  font-family: sans-serif;
}

.glitch-dot {
  position: absolute;
  top: 0; left: 0;
  width: 10px; height: 10px;
  background: #fff;
  border-radius: 50%;
  pointer-events: none;
  transform: translate(-50%, -50%);
  opacity: 0;
}

.glitch-ring {
  position: absolute;
  top: 0; left: 0;
  width: 40px; height: 40px;
  border: 1px solid rgba(255, 255, 255, 0.5);
  border-radius: 50%;
  pointer-events: none;
  transform: translate(-50%, -50%);
  opacity: 0;
}

JavaScript

var area = document.getElementById('glitchArea');
var dot = document.getElementById('glitchDot');
var ring = document.getElementById('glitchRing');
var JITTER = 20;     // max px offset
var INTERVAL = 50;   // ms between glitch jumps
var SMOOTH = 0.1;    // ring lerp factor

var mouseX = 0, mouseY = 0;
var ringX = 0, ringY = 0;
var offX = 0, offY = 0;
var glitchTimer = null;

area.addEventListener('mousemove', function (e) {
  var rect = area.getBoundingClientRect();
  mouseX = e.clientX - rect.left;
  mouseY = e.clientY - rect.top;
});

area.addEventListener('mouseenter', function () {
  dot.style.opacity = '1';
  ring.style.opacity = '1';
  glitchTimer = setInterval(function () {
    offX = (Math.random() - 0.5) * JITTER;
    offY = (Math.random() - 0.5) * JITTER;
  }, INTERVAL);
});

area.addEventListener('mouseleave', function () {
  clearInterval(glitchTimer);
  offX = 0; offY = 0;
  dot.style.opacity = '0';
  ring.style.opacity = '0';
});

function tick() {
  ringX += (mouseX - ringX) * SMOOTH;
  ringY += (mouseY - ringY) * SMOOTH;
  // Dot and ring are shoved in opposite directions, plus a skew on the ring
  dot.style.left = (mouseX - offX) + 'px';
  dot.style.top = (mouseY - offY) + 'px';
  ring.style.left = (ringX + offX) + 'px';
  ring.style.top = (ringY + offY) + 'px';
  ring.style.transform = 'translate(-50%, -50%) skew(' + offX + 'deg)';
  requestAnimationFrame(tick);
}
requestAnimationFrame(tick);