티스토리 뷰

반응형

[javascript/html] 이미지 시퀀스 플레이어 개선 버전(pre load 등)(드래그버전, 휠버전 포함)

 

 

https://css-tricks.com/lets-make-one-of-those-fancy-scrolling-animations-used-on-apple-product-pages/

 

Let's Make One of Those Fancy Scrolling Animations Used on Apple Product Pages | CSS-Tricks

Apple is well-known for the sleek animations on their product pages. For example, as you scroll down the page products may slide into view, MacBooks fold open

css-tricks.com

preload 처리와 시퀀스리소스를 위에 링크에서 참고하였다

 

-preload를 통하여 리소스를 로드해둬서 좀 더 부드럽게 시퀀싱

-requestAnimationFrame를 활용하여 애니메이션 성능 개선

 

속도가 매우 개선되었음을 확일 할 수 있다

 

테스트 영상

const html = document.documentElement;
const canvas = document.getElementById("h");
const context = canvas.getContext("2d");
let currentPos = 0;
const frameCount = 140;
let frameIndex = 0;
let isDrag = false;

const dragTrue = (e) => {
    isDrag = true;
    currentPos = e.pageX;
  };
  
  const dragFalse = (e) => {
    isDrag = false;
  };

const currentFrame = index => (
    `https://www.apple.com/105/media/us/airpods-pro/2019/1299e2f5_9206_4470_b28e_08307a42f19b/anim/sequence/large/01-hero-lightpass/${index.toString().padStart(4, '0')}.jpg`
  )

  //사전에 리소스를 로드한다
  const preloadImages = () => {
    for (let i = 1; i < frameCount; i++) {
      const img = new Image();
      img.src = currentFrame(i);
    }
  };


  const img = new Image()
img.src = currentFrame(1);
canvas.width=1280;
canvas.height=720;
img.onload=function(){
  context.drawImage(img, 0, 0);
}

const updateImage = index => {
    img.src = currentFrame(index);
    context.drawImage(img, 0, 0);
  }
  
  function printMousePos(e) {
    var cursorX= e.pageX;

    if(isDrag){
        let moveX = e.pageX - currentPos;
  //방향
  if (moveX > 0) {
    //양수
    frameIndex++;
  } else {
    //음수
    frameIndex--;
  }
        //끝점 처리
        if (frameIndex > frameCount) {
            frameIndex = frameCount;
          } else if (frameIndex < 0) {
            frameIndex = 0;
          }

        requestAnimationFrame(() => updateImage(frameIndex + 1))
        currentPos = e.pageX;
          document.getElementById('pt').innerText = ((frameIndex/frameCount)*100).toFixed(0)+"%";
    }
  }


document.addEventListener("mousedown", dragTrue);
document.addEventListener("mouseup", dragFalse);
document.addEventListener("mousemove", printMousePos);

preloadImages();

 

#preload #sequence #img #이미지시퀀스 #javascript #canvas

반응형
댓글
반응형