Вот как я бы это сделал: вместо использования события scroll
я бы использовал событие wheel
в элементе svg.Но, грубо говоря, это может быть не то, что вам нужно.
При использовании wheel
в элементе svg вы можете прокрутить позицию элемента svg на странице.Затем вы катите SVG.Несмотря на то, что над элементом svg страница не будет двигаться, треугольник будет рисовать сам.Затем вы можете продолжить прокрутку страницы.
//the SVG element
let svg = document.querySelector("svg");
// the total length of the path
let l = thePath.getTotalLength();
//the initial value for the stroke-dasharray
let dasharray = l;
//the initial value for the stroke-dashoffset
let dashoffset = l;
// styling the path
thePath.style.strokeDasharray = dasharray;
thePath.style.strokeDashoffset = dashoffset;
// on mouse wheel
svg.addEventListener("wheel",(e)=> {
e.preventDefault();
if (dashoffset > 0 && e.deltaY > 0 ||
dashoffset < l && e.deltaY < 0) {
dashoffset -= e.deltaY;
}
if(dashoffset < 0)dashoffset = 0;
if(dashoffset > l)dashoffset = l;
thePath.style.strokeDashoffset = dashoffset;
}, false);
body {
height: 2000px;
background: #f1f1f1;
}
#mySVG {
top: 15%;
width: 400px;
height: 210px;
margin-left:-50px;
border:1px solid;
}
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>
<h2>Scroll down this window to draw a triangle.</h2>
<svg id="mySVG">
<path id="thePath" fill="none" stroke="red" stroke-width="3" id="triangle" d="M150 0 L75 200 L225 200 Z" />
</svg>