刚接触AnimationFrames,画新的时候需要删除之前的图片,怎么办?

New to AnimationFrames, Need to delete previous image when new one is drawn, how?

希望你能帮助我。我刚开始使用 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()```

试试这个:context.clearRect(0, 0, canvas.width, canvas.height); 在调用 drawImage 之前

已解决:使用 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);
}```