Create animated Shaders with React Fiber using Threejs
In this post, we are going to create an hover image transition in React Fiber using Threejs. Here, we are going to show nice animations when hover over images.
This post have been inspired by this awesome YouTube video by Wawa Sensei.
To start first get the starter pack from here. After that clone the project using the below command.
Once the folder is created, change to it and then do yarn to install the npm packages. Also, do yarn dev to start the project.
Here, we have a basic React Three fiber project showing a cube.
There are a lot of React Three example projects on the official site. We are going to use the Shadermaterials project.
On opening the project, it shows nice animation effect when we hover over the image.
Back in our project, we will create textures folder inside the public folder. Here, we have put four images one is a portrait and other full body. These can be taken from the GitHub repo at the end of this article.
We will now create displacement folder inside the textures folder. And add two files for transition.
Back to the project in our App.jsx we have the Canvas showing the camera position, a background and call to an Experience component.
Back to our Shadersmaterials sandbox, we will copy most of the code.
Now, we will create a new file called FadingDisplacement.jsx and here, we will first import the required things.
After that we have added the code of ImageFadeMaterial, which we got from the sandbox.
Next, our export will also contain code from the sandbox.
Lastly in the same FadingDisplacement.jsx file, we will add our images.
Now, we will add our FadingDisplacement component in our Experience.jsx file.
Now, in our localhost, we can see the image with animation.
But the camera position was not correct, so we will fix the same by changing the position and fov in App.jsx file.
Now, our image looks perfect and the hover effect also works.
Now, our code was not highlighting properly, so we will add the Comment tagged templates extension.
For code highlighting, we have to add the comment /*glsl*/ before the targeted code.
In the Fading code, we can control the direction of the hover effect. Here, we have changed to have the hover effect from the y axis.
We have also made the hover effect last a bit longer by changing the duration.
Now, we will create another component called FadingImage.jsx, but here the animation will be on x axis.
Now, we will add props in this file and also add different images.
We will also introduce props in our FadingDisplacement.jsx file.
Now, we will add both component with positions in Experience.jsx file
Now, we will see these beautiful animations while hovering over images.
The code for the same can be found here.