개발일기

[TIL] 죽어있는 웹사이트에 생명 불어넣기

synun 2023. 2. 8. 23:46

프로젝트가 게임인데 꽤 밋밋하다는 피드백이 있었다.

 

해결책은 이 세가지 정도 있을 수 있다.

1. 효과음 넣기

2. 애니메이션 넣기

3. 인터렉션 넣기

 

인터렉션은 디자인 및 여러가지 기획이 필요하기 때문에 당장에는 어렵고

1, 2번을 넣어보도록하자!

 

효과음 넣기

react에서 효과음 넣기 괜찮은 라이브러리를 발견해서 공부해본다.

 

use-sound

 

GitHub - joshwcomeau/use-sound: A React Hook for playing sound effects

A React Hook for playing sound effects. Contribute to joshwcomeau/use-sound development by creating an account on GitHub.

github.com

오디오 재생 관련 라이브러리로 유명한 howler.js를 기반으로 만들어진 라이브러리이다.

 

import useSound from 'use-sound';

import boopSfx from '../../sounds/boop.mp3';

const BoopButton = () => {
  const [play] = useSound(boopSfx);

  return <button onClick={play}>Boop!</button>;
};

다음과 같이 훅의 형태로 쉽게 소리를 재생시킬 수 있어서 간단하게 효과음을 실행시키고 싶다면 사용하기 적합한 라이브러리가 될 수 있다.

 

이 라이브러리의 다양한 사용 방법에 대해서는  joshwcomeau 블로그에서 정말 재밌게 다루고 있으니까 보면 너무 재미있다.

 

Announcing “use-sound”, a React Hook for Sound Effects

By and large, using the web is a visual experience. This is in terrible contrast to mobile apps, which interact with three of our human senses (sight, sound, and touch, through haptic feedback). I just released a library to make it easy to add sound to you

www.joshwcomeau.com

스토리북으로 컴포넌트를 만들어서 사용예시를 볼 수 있다.

 

Storybook

 

use-sound.netlify.app

 

하지만 나는 그냥 howler.js로 커스텀훅을 만들어서 사용했다.

사운드관련 npm 라이브러리 중에서는 상당히 유명하고 강력한 라이브러리이다.

 

GitHub - goldfire/howler.js: Javascript audio library for the modern web.

Javascript audio library for the modern web. Contribute to goldfire/howler.js development by creating an account on GitHub.

github.com

howler.js는 오디오 객체를 만들어서 사용하는 것과 사용법에서 크게 차이가 없으며

모든 코덱과 크로스 브라우징 및 소리를 이용한다면 편리한 기능들을 지원하고 있어서 소리 관련으로는 라이브러리를 사용하는 것이 좋아보인다.

// useSound.jsx
import { useEffect, useRef } from 'react';
import { useSelector } from 'react-redux';
import turnOnSound from '../utils/turnOnSound';

const useSound = (src) => {
  const soundRef = useRef(null);
  const volume = useSelector((state) => state.sound.volume);

  useEffect(() => {
    soundRef.current = new Howl({ src });
  }, [src]);

  useEffect(() => {
    soundRef.current.volume(volume);
  }, [volume]);

  return soundRef;
};

export default useSound;

소리를 조절하는 기능이 있어서 세팅을 반영할 수 있도록 훅을 만들었다.

// 사용
const soundRef = useSound(src);
// 사운드 실행
soundRef.current.play();

 

애니메이션 넣기

css로 애니메이션 넣는 건 누구나 다 알지만 너무 힘들다.

사라지는 애니메이션의 경우에는 DOM에서 사라지기 이전에 애니메이션 시간을 계산해서 미리 보여주도록 해야한다.

하지만 이걸 조금 더 쉽게 사용할 수 있도록 해주는 라이브러리가 있다.

 

framer-motion

 

GitHub - framer/motion: Open source, production-ready animation and gesture library for React

Open source, production-ready animation and gesture library for React - GitHub - framer/motion: Open source, production-ready animation and gesture library for React

github.com

내가 정말정말 좋아하는 라이브러리인 framer-motion이다.

 

포브스 선정 공식문서 보기 제일 재밌는 라이브러리 1위

 

Documentation | Framer for Developers

An open source, production-ready motion library for React on the web.

www.framer.com

공식 문서에 보면 자세한 예시를 웹사이트에서 직접 인터렉션하면서 볼 수 있고 코드도 다양하게 지원하고 있다.

 

애니메이션은 공식문서를 잘 살펴보면 될 것 같고, 제일 유용했던 것은 AnimatePresence라는 컴포넌트 였는데.

    {isVisible && (
      <div>
      	{animation}
      </div>
    )}

 

 

위와 같은 경우에는 isVisible에 따라서 컴포넌트가 그려지고 사라지는데, 이런 경우에는 사라지는 애니메이션을 넣기가 상당히 까다롭다. 하지만 AnimatePresence를 사용하게 되면 엄청나게 간단해진다.

import { motion, AnimatePresence } from "framer-motion"

export const MyComponent = ({ isVisible }) => (
  <AnimatePresence>
    {isVisible && (
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
      />
    )}
  </AnimatePresence>
)

애니메이션이 있는 컴포넌트를 감싸주면 사라질 때 애니메이션이 먼저 보여지게 할 수 있다.

 

1. 모달 나타나고 사라지는 애니메이션

2. 모달이 생길 때 올라오고 사라질때 내려가는 애니메이션

3. 모달에 마우스가 hover되면 opacity가 생기고 마우스가 내려가면 opacity가 없어지는 애니메이션

 

세가지를 정말 쉽게 적용할 수 있었다.

 

이제야 좀 웹사이트가 살아움직이는 것 같다.