Syntax error How to draw on scroll using JavaScript and SVG?

How to draw on scroll using JavaScript and SVG?



To draw on scroll using JavaScript and SVG, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      height: 2000px;
      background: #f1f1f1;
   }
   svg {
      position: fixed;
      top: 15%;
      width: 400px;
      height: 210px;
      margin-left: -50px;
   }
</style>
</head>
<body>
<h1>Scroll Using JavaScript and SVG example</h1>
<svg>
<path
fill="none"
stroke="purple"
stroke-width="5"
id="polygon"
d="M 150 350 Q 150 50 250 150 Q 250 550 300 150 Q 350 50 400 300"/>
</svg>
<script>
   var polygon = document.getElementById("polygon");
   var length = polygon.getTotalLength();
   polygon.style.strokeDasharray = length;
   polygon.style.strokeDashoffset = length;
   window.addEventListener("scroll", drawPoly);
   function drawPoly() {
      var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) /
(document.documentElement.scrollHeight - document.documentElement.clientHeight);
      var draw = length * scrollpercent;
      polygon.style.strokeDashoffset = length - draw;
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On scrolling to the bottom of the page −

Updated on: 2020-05-08T12:48:13+05:30

538 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements