Categories
#SVG Web development

SVG Draw on Scroll

SVG Draw on Scroll

Using SVG and JavaScript to draw a heart on scroll. Note that it has to be a <path> element:

*animation opened in the Safari browser.
To see the live output click here.

Step1.

Add HTML

Get a SVG path

To make this animation working it has to be a path (any other of SVG elements won’t work).

To create an animation I drew a path (heart) in Adobe Illustrator. To read more about SVG and learn how to create a SVG file click here and here.

<div class="container">
<div class="text"><h1>Scroll to draw</h1></div>
  
  
<svg id="heart" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 348.43 311.23"><defs><style>.heart{fill:none;stroke:#be1622;stroke-miterlimit:10; }</style></defs><title>heart</title><path id="heart1" class="heart" d="M340.67,131.25c18.71-30.63,56.59-48.3,92.07-43s66.5,33.36,75.38,68.13c6.22,24.37,2.19,50.32-5.52,74.26-3.88,12.06-8.72,23.89-15.53,34.57s-15.51,20.05-24.35,29.15a861.3,861.3,0,0,1-120.45,103c-32.42-26.2-66.67-45.07-97.36-71.12-14.78-12.55-27.69-27.18-39.75-42.36-15.45-19.44-29.86-40.37-36.88-64.19-8.22-27.87-5.39-59.21,9.37-84.24C194.56,106.85,227,88,260.28,87.45s63.31,15.29,81.13,43.43Z" transform="translate(-163.24 -86.84)"/></svg>
  
</div>

Step2.

Add CSS

body {
  background: linear-gradient(141deg, #f0f3bd 0%, #02c39a 51%, #00a896 75%);
  display: flex;
  justify-content: center;
  align-items: center;
  height: 5000px;
  
}

.container {
  position: relative; 
}

svg {
  stroke-width: 2px;
  position: fixed;
  width: 200px;
  height: auto;
  margin:0;
  top: 30%;
  left: 45%;
}

.text {
  position: absolute;
  top:-2500px;
  display: block;
  color: white;
  width:400px;
  left:-100px;
  text-shadow: 1px 1px 1px black;
}

Step3.

Add JavaScript

const svg = document.getElementById("heart1");
const length = svg.getTotalLength();


svg.style.strokeDasharray = length;

svg.style.strokeDashoffset = length;

window.addEventListener("scroll", function () {
  const scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);

  const draw = length * scrollpercent;

  svg.style.strokeDashoffset = length - draw;

});

To see the live output check my Codepen.

Enjoy coding!