티스토리 뷰
WebPublisher/JavaScript & jQuery
[SVG] stroke-dasharray와 stroke-dashoffset을 활용한 파이 차트 프로그레스바 만들기
amanda 2025. 5. 9. 14:39HTML
<div class="bow_wrap">
<div class="item" data-percent="0">
<figure>
<svg viewBox="0 0 180 174" xmlns="http://www.w3.org/2000/svg">
<path d="M32.0055 168.5C-92.5 -41.5 275.501 -55.7932 146.006 168.5"/>
</svg>
</figure>
<span class="text">0%</span>
</div>
<div class="item" data-percent="50">
<figure>
<svg viewBox="0 0 180 174" xmlns="http://www.w3.org/2000/svg">
<path d="M32.0055 168.5C-92.5 -41.5 275.501 -55.7932 146.006 168.5"/>
</svg>
</figure>
<span class="text">50%</span>
</div>
<div class="item" data-percent="100">
<figure>
<svg viewBox="0 0 180 174" xmlns="http://www.w3.org/2000/svg">
<path d="M32.0055 168.5C-92.5 -41.5 275.501 -55.7932 146.006 168.5"/>
</svg>
</figure>
<span class="text">100%</span>
</div>
</div>
CSS
.bow_wrap{display: flex;}
.bow_wrap .item{width: 100%;max-width: 180px;background: url('bow_bg.svg') no-repeat top center / contain;/*aspect-ratio: 180 / 174;*/}
.bow_wrap .item figure{margin: 0;padding: 0;}
.bow_wrap .item path {fill: none;stroke-width: 10;stroke-linecap: round;}
.bow_wrap .item:nth-child(1) path{stroke: red;}
.bow_wrap .item:nth-child(2) path{stroke: blue;}
.bow_wrap .item:nth-child(3) path{stroke: violet;}
JavaScript
document.querySelectorAll('.item').forEach(item => {
const percent = parseFloat(item.dataset.percent) / 100;
const path = item.querySelector('path');
const length = path.getTotalLength();
path.style.strokeDasharray = length;
path.style.strokeDashoffset = length * (1 - percent);
});
getTotalLength()로 path의 총 길이를 구해준뒤
path에 stroke-dasharray 속성으로 총 길이를 넣어준다
프로그레스바의 퍼센트 비율은 stroke-dashoffset 속성에 넣어준다
완성된 모습
반원보다 살짝 더 채워진 모양으로 svg 만들고자 했으나 피그마 path로 곡선 만드는 것이 너무 어려웠다
대강 비슷한 모양으로 만들어봤는데 성공 !
'WebPublisher > JavaScript & jQuery' 카테고리의 다른 글
[youtube] 유튜브 구간 반복 재생 api 삽입 (0) | 2025.03.03 |
---|---|
[jQuery] scroll 시 해당 section에 active 클래스 추가 (0) | 2024.11.14 |
[jQuery] 따라다니는 내비게이션 sticky navigation menu (0) | 2024.11.14 |
[javaScript] jQuery로 modal 창 띄우기 (0) | 2024.11.08 |
[javaScript] 페이지를 따라다니는 하단 띠 배너 (0) | 2024.11.08 |
공지사항