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

Time:09-17

Hoping you can help me. I'm new to using AnimationFrames (started using to meet business requirements). I have managed to make an animation that changes as you scroll (via very helpful codepens) but the issue i have is that it's just adding a new image, and leaving the previous image behind, leaving a trail. (can be seen here: https://aimtechnologies.com/scrolltest/index). I know there's CancelAnimationRequest but im not sure where to put it in to solve my issue?

See below for the code:

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()```

CodePudding user response:

Try this: context.clearRect(0, 0, canvas.width, canvas.height); right before you call drawImage

CodePudding user response:

Solved: Use JPG's instead of PNGs

Or if you need to use pngs change

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