sm 기술 블로그

[리액트 React] 특수효과 (폭죽) 본문

리액트

[리액트 React] 특수효과 (폭죽)

sm_hope 2022. 5. 26. 21:31

UI 찾기

https://nextui.org/
[UI를 다루는 사이트 -> 버튼 모양, 로딩중등 다양한 UI가 있으니 나중에 꾸밀때 쓰면 좋을 듯]

위사이트에 들어가면, 특정 버튼을 눌렀을 때 발생하는 이벤트 내용이 있다.

import React from 'react';
import { Button } from '@nextui-org/react';
import confetti from 'canvas-confetti';

const CustomButton = () => {
  const handleConfetti = () => {
    confetti({...});
  };

/*생략*/

export default CustomButton;

여기서 내용이 중요한것이 아닌 canvas-confetti 라는 npm이 중요하다.

이렇게 자신이 사용하고 싶은 npm을 불러와서 개발을 진행할 수 있다.

canvas-confetti 는 색종이가 퍼지는(날라가는) 이펙트로 그 중 폭죽효과를 사용해보겠다.

npm 내용 보기

[ https://www.npmjs.com/package/canvas-confetti ]
위 사이트에 들어가면 깃 저장소의 링크가 있다.
[ https://www.kirilv.com/canvas-confetti/ ]
효과를 만든 개발자가 사용법, 설명, 다양한 효과를 올린것으로 필요한 부분을 사용하면된다.

리액트에서 폭죽효과 셋팅하기

  • HTML
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.5.1/dist/confetti.browser.min.js"></script>
  • JS
function firework() {
  var duration = 15 * 100;
  var animationEnd = Date.now() + duration;
  var defaults = { startVelocity: 25, spread: 360, ticks: 50, zIndex: 0 };
  //  startVelocity: 범위, spread: 방향, ticks: 갯수

  function randomInRange(min, max) {
    return Math.random() * (max - min) + min;
  }

  var interval = setInterval(function () {
    var timeLeft = animationEnd - Date.now();

    if (timeLeft <= 0) {
      return clearInterval(interval);
    }

    var particleCount = 50 * (timeLeft / duration);
    // since particles fall down, start a bit higher than random
    confetti(
      Object.assign({}, defaults, {
        particleCount,
        origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 }
      })
    );
    confetti(
      Object.assign({}, defaults, {
        particleCount,
        origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 }
      })
    );
  }, 250);
}

셋팅이 끝났다.
firework라는 함수를 실행하면 폭죽효과가 발생한다.

메롱 버튼을 누르면 폭죽효과 발생

https://codepen.io/denist2322/pen/WNMXBrW?editors=0100

Comments