A very simple implementation of projection mapping done in React using glsl shaders, works on any typer of surface and also moving or spinning!
You can check it out in the following sandbox -> https://codesandbox.io/s/czxbw
A breif look at the scene set up in react:
In just a few lines of code I create the scene for our project as a React component:
First I import the necessary libraries, the CameraHelper from threejs so we can show some gizmos on the camera we use to project the texture.
The react-three-fiber and drei are imported to make our life easier, as they provide the components from three js library in the best possible way readied for React.
Take a look at the whole code and I will explain under the code section each part.
Line 11 and 21 are definitions for the two nice spheres I texture with an earth and a sky texture(just so the scene won't be empty :) )
The real magic happens on line 31 onwards when I use the component I created below by extending the shaderMaterial class, I bring the code below.
What is important here to note is that we need a camera and its coordinates so I define the camera object on line 55 and update the coordinates in the useFrame handle. This information is then fed to the projectedMaterial component called in line 58.
We also need a simple texture and a color for the base of the mesh for the areas that there is no projection done on and these are defined on lines 35 and 37 respectively.
A simple shader to rule them all
The shaderMaterial class is a gateway to any shader implementation in Three js, you can quite easily give all the components you use in your shader as uniforms in the constructor and then provide a fragment and a vertex shader.
Here we get the coordinates from a camera and change the uv coordinates of our texture according to that on each frame.
I hope this was useful for you, please leave comments if you needed more information!