Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript와 SVG로 스크롤에 따라 선을 그리는 방법

JavaScript와 SVG를 활용하면 사용자가 페이지를 스크롤할 때마다 SVG 경로(path)가 점진적으로 그려지는 시각적 효과를 쉽게 구현할 수 있습니다. 핵심 원리는 SVG의 stroke-dasharraystroke-dashoffset 속성을 이용하는 것입니다.

동작 원리


  • getTotalLength(): SVG 경로의 전체 길이를 픽셀 단위로 반환합니다.
  • stroke-dasharray: 선을 점선 형태로 만들어, 경로 전체 길이만큼 설정하면 선 하나가 통째로 하나의 대시가 됩니다.
  • stroke-dashoffset: 대시의 시작 위치를 조정합니다. 값을 경로 길이와 같게 하면 선이 완전히 숨겨지고, 0으로 줄어들수록 선이 그려집니다.
  • scroll 이벤트: 스크롤 진행률(0~1)을 계산한 뒤, 이 비율만큼 dashoffset을 감소시켜 스크롤과 연동된 드로잉 효과를 만듭니다.


예제 코드

<!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>

코드 설명


  1. 먼저 getElementById()로 SVG path 요소를 가져옵니다.
  2. getTotalLength() 메서드로 경로의 전체 길이를 계산합니다.
  3. strokeDasharraystrokeDashoffset을 경로 길이로 설정하여 초기 상태에서는 선이 보이지 않도록 합니다.
  4. window 객체에 scroll 이벤트 리스너를 등록하고, drawPoly 함수에서 스크롤 진행률을 백분율로 계산합니다.
  5. 스크롤 비율에 비례해 strokeDashoffset 값을 줄여 나가면, 페이지를 내릴수록 보라색 곡선이 서서히 그려지는 효과가 완성됩니다.


실행 결과

위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

JavaScript와 SVG로 스크롤에 따라 선을 그리는 방법

페이지 맨 아래까지 스크롤했을 때의 모습입니다. 스크롤이 진행될수록 SVG 경로가 완전하게 그려진 것을 확인할 수 있습니다.

JavaScript와 SVG로 스크롤에 따라 선을 그리는 방법