Cursor · 10 of 22

Arrow Rotate

Arrow points in movement direction

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="arrow-area" id="arrowArea">
  <h2>Direction</h2>
  <div class="cursor-arrow" id="cursorArrow"></div>
</div>

CSS

.arrow-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;
}

/* CSS triangle pointing up; JS rotates it toward the movement direction */
.cursor-arrow {
  position: absolute;
  top: 0; left: 0;
  width: 0; height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 20px solid #7c5cff;
  pointer-events: none;
  transform-origin: center;
  opacity: 0;
}

JavaScript

var area = document.getElementById('arrowArea');
var arrow = document.getElementById('cursorArrow');
var MIN_MOVE = 3;   // px — ignore sub-pixel jitter
var TURN = 0.25;    // rotation smoothing factor

var lastX = 0, lastY = 0;
var angle = 0;        // smoothed angle actually rendered
var targetAngle = 0;  // latest raw movement angle

area.addEventListener('mouseenter', function (e) {
  lastX = e.clientX;
  lastY = e.clientY;
  angle = targetAngle;
  arrow.style.opacity = '1';
});
area.addEventListener('mouseleave', function () {
  arrow.style.opacity = '0';
});

area.addEventListener('mousemove', function (e) {
  var rect = area.getBoundingClientRect();
  var dx = e.clientX - lastX;
  var dy = e.clientY - lastY;
  if (Math.sqrt(dx * dx + dy * dy) > MIN_MOVE) {
    targetAngle = Math.atan2(dy, dx) * 180 / Math.PI + 90;
    lastX = e.clientX;
    lastY = e.clientY;
  }
  arrow.style.left = (e.clientX - rect.left) + 'px';
  arrow.style.top = (e.clientY - rect.top) + 'px';
});

function tick() {
  // Rotate along the shortest path so diagonals don't spin the long way round
  var diff = targetAngle - angle;
  diff = ((diff + 180) % 360 + 360) % 360 - 180;
  angle += diff * TURN;
  arrow.style.transform = 'translate(-50%, -50%) rotate(' + angle + 'deg)';
  requestAnimationFrame(tick);
}
requestAnimationFrame(tick);