류림스 공간

[항해99 76일차] 2022.05.21 TIL (리액트 gsap라이브러리 사용하여 애니메이션 효과 구현) 본문

TIL/2022 TIL

[항해99 76일차] 2022.05.21 TIL (리액트 gsap라이브러리 사용하여 애니메이션 효과 구현)

ryurim 2022. 5. 21. 21:18
반응형

오늘은 이런 애니메이션 효과를 구현해보았다!!!

 

맨처음에는 어떻게 해야될지 사실 감이 잘 오지 않았다.

예전에 바닐라 자바스크립트 배울 시절..

애니메이션 구현은 gsap을 사용하여 구현했던 기억이 스물스물 올라왔지만,,

이걸 어떻게 리액트에 적용시켜..ㅠㅠ

이러한 생각이 먼저였다.

 

하지만 gsap공식 문서를 ..계속 뒤지다가 뒤지다가 발견한..

리액트에서 gsap라이브러리 사용하는 문서를 보았다.

 

우선 라이브러리를 설치한다.

 

yarn add gsap

 

위의 화면을 구현하기 위한 app.js 코드

import React, { useRef, useEffect, useState } from "react";
import styled from "styled-components";
import { gsap } from "gsap";
//우선 임포트 먼저!

function App() {
  const textRef = useRef();
  const text2Ref = useRef();
  const [active, setActive] = useState(true);
  useEffect(() => {
    const timeout = setTimeout(() => remove(), 2000);
    return () => clearTimeout(timeout);
  }, [textRef]);
  useEffect(() => {
    const timeout = setTimeout(() => show(), 4000);
    return () => clearTimeout(timeout);
  }, [text2Ref]);

  const remove = () => {
    const ani = gsap.to(textRef.current, {
      x: -773,
      display: "none",
      duration: 1,
      ease: "strong.inOut",
      onComplete: () => setActive(false),
    });
    return () => {
      ani.kill();
    };
  };
  const show = () => {
    const ani2 = gsap.to(text2Ref.current, {
      x: 863,
      duration: 1,
      ease: "strong.inOut",
    });
    return () => {
      ani2.kill();
    };
  };
  return (
  <>
  	<Background>
      <TextImg ref={textRef} />
      {!active && <Text02Img ref={text2Ref} />} //위의 요소가 사라지면 나타나게 해!
        </Background>
        </>
  );
}

const Background = styled.div`
  width: 100vw;
  height: 100vh;
  background-image: url(${backgroundImg});
  background-size: cover;
  overflow: hidden;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
`;
const TextImg = styled.div`
  width: 683px;
  height: 373px;
  background-image: url(${textImg});
  background-size: cover;
  position: fixed;
  bottom: 90px;
  left: 90px;
`;
const Text02Img = styled.div`
  width: 690px;
  height: 373px;
  background-image: url(${textImg02});
  background-size: cover;
  position: fixed;
  bottom: 90px;
  left: -773px;
`;

두 시간 정도 고민했던 것 같다.

화면 키자마자 바로 애니메이션이 실행되면 조금 어설플 수 있으니

2000ms 시간이 지난 이후 1개 실행되고,

그 하나의 애니메이션이 실행된 다음

2번째 애니메이션을 실행시켜줬다.

 

공부가 더 필요할 것 같지만,,,그래도 디자이너님이 원하시는 대로 구현을 해서 다행이다.ㅠㅠㅠ

728x90
반응형
Comments