
w3.css
스크롤 드로잉
JavaScript와 SVG를 이용해 스크롤에 그리는 방법을 알아보자.
스크롤 드로잉 그리기
스크롤 시 삼각형을 그리기 위해 SVG와 JavaScript를 사용한다. <path> 요소여야 한다.
1단계) HTML 추가
<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 id of the <path> element and the length of <path> var triangle = document.getElementById("triangle"); var length = triangle.getTotalLength(); // The start position of the drawing triangle.style.strokeDasharray = length; // Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw triangle.style.strokeDashoffset = length; // Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled window.addEventListener("scroll", myFunction); function myFunction() { var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight); var draw = length * scrollpercent; // Reverse the drawing (when scrolling upwards) triangle.style.strokeDashoffset = length - draw; } </script>
기본 예시
예제 보기참고
W3C School - How TO - Scroll Drawing