React 반짝이는 별 효과 만들기✨

Haram B·2023년 2월 16일
2

Frontend

목록 보기
4/5
post-thumbnail

포트폴리오 사이트에 들어갈 별 효과를 만들어보았다.

먼저 별 객체를 만들어준다.

class star {
  constructor(x, y, size, time) {
    this.x = x;
    this.y = y;
    this.size = size;
    this.time = time;
  }
}

x, y는 좌표, size는 별 크기, time은 반짝이는 효과가 실행되는 시간이다.
4가지를 모두 랜덤으로 생성해서 넣어줄 것이다.

javascript 코드를 작성하기 전에 html과 css만 사용해서 크기가 8x8인 별을 하나만 만들어보면 이렇게 만들 수 있다.

<div class="star"></div>
.star {
  position: relative;
  width: 8px;
  height: 8px;
  left: 1137px;
  top: 485px;
  background-color: #ffffff;
  filter: blur(5px);
  animation: blink 1s steps(5) infinite;
}

결과:


똑같이 javascript 코드를 작성해주면 되는데, 사이즈와 별의 위치, 반짝이는 시간을 랜덤으로 뽑아준다.

class star {
  constructor(x, y, size, time) {
    this.x = x;
    this.y = y;
    this.size = size;
    this.time = time;
  }

  set() {
    this.x = Math.random() * window.innerWidth;
    this.y = Math.random() * window.innerHeight;
    this.size = Math.random() * 12;
    this.time = Math.random() * 8;

    const background = document.getElementById("main");
    const starDiv = document.createElement("div");
    starDiv.className = "star";

    starDiv.style.position = "absolute";
    starDiv.style.left = this.x + "px";
    starDiv.style.top = this.y + "px";
    starDiv.style.width = this.size + "px";
    starDiv.style.height = this.size + "px";
    starDiv.style.backgroundColor = "white";
    starDiv.style.filter = "blur(5px)";
    starDiv.style.animation = `blink ${this.time}s steps(5) infinite`;

    background.appendChild(starDiv);
  }
}

마지막으로 React의 useEffect라는 Hooks를 사용해서 사이트가 렌더링 될 때 별 객체 15개를 만들어서 띄워준다.

  • useEffect는 원래 상태가 변경될 때마다 실행되지만 마지막에 빈 배열을 넣어주면 렌더링 될 때 한번만 실행된다.
useEffect(() => {
    for (let i = 0; i < 15; i++) {
      const newStar = new star();
      newStar.set();
    }
  }, []);

결과물

새로고침 할 때마다 (사이트가 렌더링 될 때마다) 15개의 별이 다른 좌표, 다른 사이즈로 만들어진다.
반짝이는 속도도 각각 다르기 때문에 더 반짝 반짝한 느낌이 든다
아주 간단하게 반짝이는 화면 구현 끝_!

➕ div로 만들었기 때문에 별의 모양이 자세히 보면 네모에 가깝다..! 별을 원 모양으로 만들고 싶다면 border-radius를 50%로 지정해주면 된다.

profile
사회에 이로운 IT 기술에 대해 고민하고 모두가 소외되지 않는 서비스를 운영하는 개발자를 꿈꾸고 있습니다 ✨

0개의 댓글