여러 개의 객체에 애니메이션 적용하기

gu·2023년 7월 31일
0

Web Animation

목록 보기
5/7

💻 여러 객체에 애니메이션 적용하기


이 bar들에 효과를 주어 분수처럼 흐르는 애니메이션을 만들려고 한다. 어떤 방법들이 있는지 알아보자.

🖤 forEach

<body>
        <div class="bar-container"></div>

        <script>
            const barContainer = document.querySelector(".bar-container");
            const bars = [];
			// bar 객체선언
            let bar;
			// 반복문으로 bar30개만들어줌
            for (let i = 0; i < 30; i++) {
              
                bar = document.createElement("div");
                bar.classList.add("bar");
                barContainer.append(bar);
                bars.push(bar);
            }
            console.log(bars);
            const keyframes = [
              // 위로 쏟아올라야하므로 scale을 Y축기준으로 해준다. 
              { transform: "scaleY(0)" }, 
              { transform: "scaleY(1)" }
            ];
            const options = {
                duration: 3000,
                direction: "alternate",
              // 연속으로 흘러야하므로
                iterations: Infinity,
              // 자연스럽게 흐르기위함
                fill: "both",
                easing: "ease-in-out",
            };
            bars.forEach((bar, index) => {
                console.log("인덱스", index);
              //한타임씩 늦게 애니메이션이 시작되어야하므로 delay를 걸어줄때 인덱스번호 곱 0.2초를 해준다. 
                bar.animate(keyframes, { ...options, delay: index * 200 });
            });
        </script>
    </body>
  • Method
    -createElement() : 지정된 HTML 요소를 생성
    -classList.add(): 생성되있는 클래스 추가
    -.append(): Node 객체로 자식 요소를 설정할 수 있을 뿐만 아니라, text를 사용할 수도 있다.

🖤 groupEffect

<body>
        <div class="bar-container"></div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.2/web-animations-next.min.js"></script>
        <script>
            const barContainer = document.querySelector(".bar-container");
            const bars = [];

            let bar;
            for (let i = 0; i < 30; i++) {
                bar = document.createElement("div");
                bar.classList.add("bar");
                barContainer.append(bar);
                bars.push(bar);
            }
            console.log(bars);
            const keyframes = [{ transform: "scaleY(0)" }, { transform: "scaleY(1)" }];
            const options = {
                duration: 3000,
                direction: "alternate",
                iterations: Infinity,
                fill: "both",
                easing: "ease-in-out",
            };

            const effects = [];
            bars.forEach((bar, index) => {
                const newOptions = { ...options, delay: index * 200 };
                const effect = new KeyframeEffect(bar, keyframes, newOptions);
                effects.push(effect);
            });

            const groupEffect = new GroupEffect(effects);
            const animation = document.timeline.play(groupEffect);

            // 애니메이션 정지
            // setTimeout(() => {
            //     animation.pause();
            // }, 3000);
        </script>
    </body>

글쓰는 현재까지는 그룹이펙트를 하려면 외부 스크립트를 가져와야한다.
Web-animations에서 스크립트를 가져와 구현했다.

GroupEffect는 여러 효과가 그룹으로 함께 애니메이션되는 복잡한 애니메이션 효과를 생성할 수 있는 기술이다. 그룹화는 그룹 내부의 복잡성을 숨겨 복잡한 트리 구조를 생성할 수 있는 강력한 메커니즘이다. 이것이 제대로 작동하려면 그룹이 내부작업을 숨기고 공통 API를 노출해야한다.

  • 자식효과의 정렬된 목록을 포함하지만 부모에서 자식으로 시간 매핑 및 고유한 반복 기간이 아닌 추상 클래스다. 특정 시간 매핑모델이 있는 몇가지 구체적인 하위클래스가 있다.
    -ParallelEffect:모든 차일드가 동시에 시작하며 교대가 없다.
    -SequenceEffect: 각 자식이 차례로 시작(순서가 중요)
    -StaggerEffect:각 자식은 스태거 구성에 따라 시간 지연 후에 시작

🖤 SequenceEffect

<body>
        <div class="bar-container"></div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.2/web-animations-next.min.js"></script>
        <script>
            const barContainer = document.querySelector(".bar-container");
            const bars = [];

            let bar;
            for (let i = 0; i < 30; i++) {
                bar = document.createElement("div");
                bar.classList.add("bar");
                barContainer.append(bar);
                bars.push(bar);
            }
            console.log(bars);
            const keyframes = [{ transform: "scaleY(0)" }, { transform: "scaleY(1)" }];
            const options = {
                duration: 500,
                direction: "alternate",
                // iterations: Infinity,
                fill: "both",
                easing: "ease-in-out",
            };

            const effects = [];
            bars.forEach((bar, index) => {
                const effect = new KeyframeEffect(bar, keyframes, options);
                effects.push(effect);
            });

            const sequenceEffect = new SequenceEffect(effects);
            const animation = document.timeline.play(sequenceEffect);

            // 애니메이션 정지
            // setTimeout(() => {
            //     animation.pause();
            // }, 3000);
        </script>
    </body>

-document.timeline: 타임라인 기능을 정의하기 위해 존재하며 개발자가 자체적으로 엑세스하지 않는다.

참고자료

group-effect설명
1분코딩

0개의 댓글