How to Draw While Scrolling

Learn how to draw while scrolling using JavaScript and SVG.

Try It Yourself

Scrolling Drawing

Using SVG and JavaScript to draw triangles while scrolling - please note, it must be <path> Element: }}

Instance

<svg id="mySVG">
  <path fill="none" stroke="red" stroke-width="3" id="triangle" d="M150 0 L75 200 L225 200 Z"/>
</svg>
<script>
// Get the <path> element with ID "triangle"
var triangle = document.getElementById("triangle");
// Get the length of the <path> element
var length = triangle.getTotalLength();
// Starting position for drawing (set dashed mode. Here set to the same value as the path length, which actually treats the entire path as a 'large dashed line'.)
triangle.style.strokeDasharray = length;
/* Set the dashed offset. Initially set to the path length to offset the entire path out of view, thereby hiding the triangle.
As the scrolling progresses, this offset will gradually decrease, thereby gradually revealing the triangle.
Removing this line of code can display the triangle before the scrolling drawing.
triangle.style.strokeDashoffset = length;
// Listen for the window scroll event and call the myFunction function when scrolling.
window.addEventListener("scroll", myFunction);
function myFunction() {
  // Calculate the scroll percentage = (current scroll height) / (total scrollable height)
  var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
  // Calculate the length to be drawn = total length * scroll percentage
  var draw = length * scrollpercent;
  // When scrolling up, it is actually drawing in reverse (from complete to incomplete), so here the total length is subtracted by the length that should be drawn.
  triangle.style.strokeDashoffset = length - draw;
}
</script>

Try It Yourself

Related Pages

Tutorial:SVG Tutorial