Web Development Kodex

draw on scroll

custom.js

'use strict'
const path = document.getElementById('line')
const length = path.getTotalLength()
const html = document.querySelector('html')
const height = html.clientHeight
const scrollHeight = html.scrollHeight
path.style.strokeDasharray = length
path.style.strokeDashoffset = length
window.addEventListener('scroll', () => {
const percentage = this.pageYOffset / (scrollHeight - height)
const draw = length * percentage
path.style.strokeDashoffset = length - draw
})

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Draw on Scroll</title>
<meta name="robots" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>JavaScript Draw on Scroll</h1>
</header>
<div class="wrapper">
<div class="container">
<svg class="scribble" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 652 560" style="enable-background:new 0 0 652 560;" xml:space="preserve">
<path id="line" d="M196.5,217.5c0,36.6-117.6,41.9-124,78C63,349.1,204,462,209.5,464.5c51,23,195-42,223-76s110-103,23-192
s-117-159-172-151s101,95,72,209s-49,143-151,131s-211-292-85-253s158,163,258,192s370-27,223-117s-145-355-247-98s71,223-123,319
s-268,91-213-21s32-233,132-239s308,271,342,290s61.6,43.4,84,38c52.7-12.8,139-155-5-217s-105,11-266,130s-251,269-189-9
s-38-387,83-353"/>
</svg>
</div>
<!-- .container-->
</div>
<!-- .wrapper-->
<footer>
<small><a href="https://opensource.org/licenses/MIT">MIT</a></small>
</footer>
<script src="custom.js"></script>
</body>
</html>

styles.css

body {
background: #eeeeee;
font-size: 16px;
font-family: "Trebuchet MS", Helvetica, sans-serif;
margin: 0;
}
a {
color: crimson;
text-decoration: none;
}
a:hover {
color: red;
}
/* Layout
------------------------------------------*/
header, .container, footer {
margin: 0 auto;
width: 88%;
max-width: 1080px;
}
.wrapper {
padding: 1em 0;
background: #ffffff;
min-height:900px;
}
/* Animated path
------------------------------------------*/
.scribble {
max-width:500px;
position:fixed;
top:20;
}
#line {
fill: none;
stroke: red;
stroke-width: 2px;
}