'Infinit Scroll without cloning in Javascript (Reset scroll position to top after reaching the bottom of the page)

I'm just starting JavaScript and still struggling a lot to reach my goals. I managed to make this little script work, which allows me to start a frame by frame animation related to the scroll of the page. My animation is a loop and I would like from now on simply that arrived at the bottom of the page the scroll restart automatically at the top of the page. So that the animation seems infinite.

I have seen some solutions with a clone of my content but it does not seem very suitable. Here is the JS as is.

Thanks in advance for your ideas!

const html = document.documentElement;
const canvas = document.getElementById("fuck");
const context = canvas.getContext("2d");

const frameCount = 100;
const currentFrame = index => (`https://www.jabberwock.archi/maquette/img/${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=1800;
canvas.height=1206;
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()

and the link of the page to see the animation :

https://jabberwock.archi/maquette/

Thank a lot !



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source