How TO - Scroll Drawing

Learn how to draw on scroll using JS and SVG.

Scroll Drawing

Using SVG and JavaScript to draw a triangle on scroll - note that it has to be a <path> element:


<svg id="mySVG">
  <path fill="none" stroke="red" stroke-width="3" id="triangle" d="M150 0 L75 200 L225 200 Z"/>

// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("triangle");
var length = triangle.getTotalLength();

// The start position of the drawing = length;

// Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw = length;

// Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled
window.addEventListener("scroll", myFunction);

function myFunction() {
  var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);

  var draw = length * scrollpercent;

  // Reverse the drawing (when scrolling upwards) = length - draw;
Try it Yourself »