stroke-dasharray / stroke-dashoffset 활용, 애니메이션 만들기
dasharray, dashoffset의 속성, 선 길이를 구하는 간단한 함수를 이용해 기초적인 애니메이션 효과를 학습할 수 있다!
우선 svg로 동그라미를 그려줌
See the Pen Untitled by yeaseula (@yeaseula) on CodePen.
1.stroke 관련 css
dasharray, dashoffset의 속성
stroke-dasharray : 점의 길이
stroke-dashoffset : 점 사이 간격의 길이
더 자세히 뜯어보자면
stroke-dasharray 숫자가 작아질수록 dash가 촘촘하다.
즉, stroke-dasharray = 선 길이 일 땐 그냥 완벽한 라인이 된다.
stroke-dashoffset 숫자가 커질수록 점과 점 사이의 간격이 넓어진다.
반대로 숫자가 작아질수록 점 사이 간격이 좁아져 결국 선으로 보여진다.
*참고 : https://observablehq.com/@shreshthmohan/svg-stroke-dasharray-stroke-dashoffset-and-pathlength
SVG stroke-dasharray, stroke-dashoffset and pathLength
Play with the controls below First, change both and see what happens Now increase stroke-dasharray to the max, and then drag stroke-dashoffset from max to min and reverse all the way. This behaviour can be used to animate SVG line paths. If we don't set pa
observablehq.com
선 길이 = stroke-dasharray
점 하나의 길이가 전체 선 길이와 같다면 결국 하나의 선으로 보인다.
이 상태에서
선 길이 = stroke-dashoffset
조건도 충족된다면?
화면엔 아무것도 보이지 않게된다
반대로 stroke-dashoffset가 0이되면 dash만 남게된다! (하나의 선으로 보임)
이런 특성을 이용해 stroke-dashoffset 값을 변화시켜서 효과를 주면 된다.
그럼이제 선 길이를 구해야 한다.
2.선 길이 구하는 함수
getTotalLength()
var cl = document.querySelector(".circle");
function circleLine(el) {
var line = el.getTotalLength();
el.style.strokeDasharray = line;
el.style.strokeDashoffset = line;
console.log(line)
}
circleLine(cl);
이제 keyframes 를 이용해 무한반복 자동재생되는 애니메이션을 만들 수 있다.
stroke-dasharray = stroke-dashoffset = 선길이로 아무것도 보이지 않는 상태로 시작,
stroke-dashoffset = 0 으로 라인만 보이도록 해서 끝!
이 애니메이션을 infinite로 무한반복한다~
결과물)
See the Pen Untitled by yeaseula (@yeaseula) on CodePen.