首页 > 解决方案 > AnimationFrames 的新手,绘制新图像时需要删除以前的图像,怎么办?

问题描述

希望你能帮助我。我是使用 AnimationFrames 的新手(开始使用以满足业务需求)。我已经设法制作了一个随着您滚动而改变的动画(通过非常有用的代码笔),但我遇到的问题是它只是添加了一个新图像,并留下了以前的图像,留下了痕迹。(可以在这里看到:https ://aimtechnologies.com/scrolltest/index )。我知道有 CancelAnimationRequest 但我不确定在哪里解决我的问题?

请参阅下面的代码:

const canvas = document.getElementById("hero-lightpass");
const context = canvas.getContext("2d");

const frameCount = 148;
const currentFrame = index => (
  `images/1 & 2 Intro & Exploded View_${index.toString().padStart(5, '0')}.png`
)

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=1158;
canvas.height=770;
img.onload=function(){
  context.drawImage(img, 0, 0);
}

const updateImage = index => {
  img.src = currentFrame(index);
  context.drawImage(img, 0, 0);
}

window.addEventListener('scroll', () => {  
  const scrollTop = html.scrollTop;
  const maxScrollTop = html.scrollHeight - window.innerHeight;
  const scrollFraction = scrollTop / maxScrollTop;
  const frameIndex = Math.min(
    frameCount - 1,
    Math.ceil(scrollFraction * frameCount)
  );
  
  requestAnimationFrame(() => updateImage(frameIndex + 1))
});

preloadImages()```

标签: javascripthtmlanimation

解决方案


已解决:使用 JPG 而不是 PNG

或者如果您需要使用 pngs 更改

  context.drawImage(img, 0, 0);
}
``` to ```img.onload=function(){
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(img, 0, 0);
}```

推荐阅读