What is the best way of doing spinning planet animation?

Hello to everybody guys! On my work i'm faced with the task of doing spinning planet animation on scroll, so the user will scroll the page and planet must spin. And i'm curious now, what is the best way to do so? I have 200+ images of planet with different angle. I was thinking to replace images on scroll via state or something like that, or use threejs, but i don't know if i can put my image there or found something similar. If you already did this in the past, please tell me how to do that in the right way. Any suggestions are welcome!
5 Replies
Chris Bolson
Chris Bolson14mo ago
As you suggest, you could do this with JavaScript by calculating the viewport height and scroll position. Something like this should work:
const globe = document.querySelector("#globe");
const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
let moveVal = 0;
window.addEventListener("scroll", () => {
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
moveVal = Math.floor((scrollTop / height) * 360);
globe.setAttribute(
"src",
`/assets/globe-${moveVal}.gif`
);
});
const globe = document.querySelector("#globe");
const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
let moveVal = 0;
window.addEventListener("scroll", () => {
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
moveVal = Math.floor((scrollTop / height) * 360);
globe.setAttribute(
"src",
`/assets/globe-${moveVal}.gif`
);
});
I have been playing with this and the issue I had was the amount of images - the browser wasn't able to change them quick enough on scroll (each image is a 2kb webp) so I modified it to only change every 10. This improved the loading but is now a bit jumpy - I need to try every 5 but have to leave it now. I wonder if I can get the image size down more...
Tok124 (CSS Nerd)
javascript is probably the best option, but you can animate on scroll using only CSS, but it' experimental feature and requires a flag to be activated. but you have animation-timeline:scroll(root); so you could give that a try
Chris Bolson
Chris Bolson14mo ago
I forgot to show you my test for this: https://spinning-globe.netlify.app/ I ended up reducing the image size to 1kb each and showing every 5. Ideally it would need some sort of preloading to load the images into the cache.
RobyDobyDingo
RobyDobyDingo14mo ago
Awesome! You did a great work! Now I'm thinking that it will be impossible to do with my image sizes, because it's almost a full screen size images with 50-80kb each
Chris Bolson
Chris Bolson14mo ago
Yes, it is not very practical. It works fine (with my1kb images) in local but on the web it’s a different matter.