Hello, today let me show you how I created the 3D scrolled animated scene of my website :
First, we want to create a WebGL scene, and to do it quickly we will use Three.js made by Mr Doob.
I will not cover the Dom & Css part on this article but you will get access to it in the embedded examples.
For this example we will use a cube :
Then we set our THREE environnement. The scene, the camera and the renderer. We then add the cube to the scene and the renderer to the dom.
As a small extra we will make it responsive because this is cool.
The scene is ready, let’s animate it ! We will make the cube rotate in every direction.
When everything is merge :
Perfect, we got everything ready to start working !
We need to initialise some variables for the scroll.
Do not forget to bind the wheel event.
On mobile we could manage this with the touchstart and touchmove events :
We cannot put the mobile events on this article because of the embedded.
Everything was pretty basic so far, now cool stuff is coming.
Smooth that thing !
This is where the magic happens. With the lerp function we can add some easing on it, the closer to 0 the “threshold → t” is, the bigger the easing will be. For a 60fps scene you should put your threshold between 0.13 to 0.18 to make it smooth. Under 0.13 it will be too much and it will feel laggy.
Now we can use that lerp function to smooth the scroll value :
For a better understanding I added the scroll value to scene (try to click then scroll in the embedded):
We got our scene, a smooth scroll, things are getting interesting. To animate everything we will use the library Animejs made by Julian Garnier.
Create the animation function and add it to the main function init(). The trick here is to use the timeline function provided by animejs and to set autoplay to false. We will increase the animation progression using our awesome smooth scroll value !
The timeline function :
With this timeline method, we could apply many easing functions inside the main easing function. But even more ! Let me give you a small example on how far we could get with this method :
Here we tween the background color in WebGL, so it’s way faster ! Tweening css colors is always a disaster in matters of performances.
Now we need to update the timeline progression in the requestAnimFrame function :
I multiply by “(timelineDuration / maxHeight)”. This way, the animation is base on 100% of the scrolling page height.
And for the final result (try to click then scroll in the embedded):
Now you can play with it ! Add animations, update objects, update the camera position/rotation, have fun !
If you found this article interesting, follow me on twitter for more @onirenaud ✌️