애니메이션 프레임 기록

Beginner

This tutorial is from open-source community. Access the source code

소개

이 랩에서는 재귀 (recursion) 와 Window.requestAnimationFrame() 메서드를 사용하여 애니메이션 프레임을 기록하고 각 프레임에서 제공된 콜백 (callback) 을 호출하는 함수를 만드는 방법을 살펴봅니다. 또한 반환된 객체의 startstop 메서드를 사용하여 기록을 수동으로 제어하는 방법도 배웁니다. 이 랩은 JavaScript 에서 애니메이션 프레임을 사용하는 방법과 보다 효율적이고 제어된 애니메이션을 만드는 방법을 이해하는 데 도움이 될 것입니다.

애니메이션 프레임 기록 가이드

애니메이션 프레임을 기록하려면 다음 단계를 따르세요.

  1. 터미널/SSH 를 열고 node를 입력하여 코딩 연습을 시작합니다.
  2. 재귀 (recursion) 를 사용하여 각 애니메이션 프레임에서 제공된 콜백 (callback) 을 호출합니다.
  3. runningtrue이면, 제공된 콜백을 호출하는 Window.requestAnimationFrame()을 계속 호출합니다.
  4. 기록을 수동으로 제어할 수 있도록 startstop의 두 가지 메서드를 가진 객체를 반환합니다.
  5. 함수가 호출될 때 start를 암시적으로 호출하려면 두 번째 인수 autoStart를 생략합니다.

애니메이션 프레임을 기록하려면 다음 코드를 사용하세요.

const recordAnimationFrames = (callback, autoStart = true) => {
  let running = false,
    raf;
  const stop = () => {
    if (!running) return;
    running = false;
    cancelAnimationFrame(raf);
  };
  const start = () => {
    if (running) return;
    running = true;
    run();
  };
  const run = () => {
    raf = requestAnimationFrame(() => {
      callback();
      if (running) run();
    });
  };
  if (autoStart) start();
  return { start, stop };
};

코드 사용 예시:

const cb = () => console.log("Animation frame fired");
const recorder = recordAnimationFrames(cb);
// logs 'Animation frame fired' on each animation frame
recorder.stop(); // stops logging
recorder.start(); // starts again
const recorder2 = recordAnimationFrames(cb, false);
// `start` needs to be explicitly called to begin recording frames

요약

축하합니다! 애니메이션 프레임 기록 랩을 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 기술을 향상시킬 수 있습니다.