Cursor · 15 of 22

Elastic Line

Line stretches to cursor

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="elastic-line-area" id="elasticArea">
  <svg class="elastic-svg" width="100%" height="100%">
    <path id="elasticPath" d="M0 100 Q 150 100 300 100" stroke="#fff" fill="none" stroke-width="2"/>
  </svg>
</div>

CSS

.elastic-line-area {
  position: relative;
  height: 200px;
  background: #12121a;
  overflow: hidden;
}

.elastic-svg { pointer-events: none; }

JavaScript

var area = document.getElementById('elasticArea');
var path = document.getElementById('elasticPath');
var LINE_Y = 100; // px — the line's resting height

area.addEventListener('mousemove', function (e) {
  var rect = area.getBoundingClientRect();
  var x = e.clientX - rect.left;
  var y = e.clientY - rect.top;
  // The cursor is the quadratic control point, bending the line toward it
  path.setAttribute('d', 'M0 ' + LINE_Y + ' Q ' + x + ' ' + y + ' ' + rect.width + ' ' + LINE_Y);
});

area.addEventListener('mouseleave', function () {
  var w = area.offsetWidth;
  path.setAttribute('d', 'M0 ' + LINE_Y + ' Q ' + (w / 2) + ' ' + LINE_Y + ' ' + w + ' ' + LINE_Y);
});