본문 바로가기

JavaScript/Canvas

requestAnimationFrame 을 지정된 시간동안 일정하게 호출하는 방법

1. setTimeout으로 1초에 30 프레임씩 render

start = (callback, fps) => {
    const seconds = 1000 / fps;

    callback();

    this.id = setTimeout(() => {
      this.start(callback, fps);
    }, seconds);
  }

 

2. requestAnimationFrame으로 1초에 30 프레임씩 render

start = (callback, fps) => {
    const frame = timestamp => {

      if (this.timestamp === 0) {
        this.timestamp = timestamp;
      }

      this.totalProgress = timestamp - this.timestamp;
      this.progress = timestamp - this.timestamp;

      if (this.progress > fps) {
        this.progress -= fps;
        this.timestamp = timestamp;

        callback(this.totalProgress / fps);
      }

      this.id = window.requestAnimationFrame(frame);
    };

    this.id = window.requestAnimationFrame(frame);
  }

'JavaScript > Canvas' 카테고리의 다른 글

canvas에 poster이미지 로드  (0) 2019.09.09