Okay, so today I wanted to mess around with creating a 3D sun in the browser. I’ve dabbled with * before, so I figured that would be a good starting point. I remember it being pretty straightforward to get basic shapes going.
First things first, I needed to get * set up. I created a new HTML file and included the * library. It’s easily to find the CDN link on google search result, I find it and added to my html page’s head tag. Then created * javascript file, also added to the html page.
Next, I jumped into my JavaScript file. I created a new scene, a camera, and a renderer. This is the basic boilerplate for any * project. The scene is where all your objects live, the camera is how you view the scene, and the renderer draws everything to the screen.
I started with a simple sphere for the sun. I used the SphereGeometry
class to define the shape and the MeshBasicMaterial
class to give it a color. I made it yellow, because, you know, it’s the sun.
- Create Scene
- Create Camera
- Create Renderer and added to my html page’s body tag.
- Create sun’s SphereGeometry and set radius, widthSegments, heightSegments
- Give the sun a basic color MeshBasicMaterial, set color yellow.
- Create Mesh and added SphereGeometry and MeshBasicMaterial to it as paramenters.
- Added Mesh to the Scene by add().
- Run and test the scene by render() and added scene and camera as paramenters.
Here’s kind of what the initial code looked like:
I ran the code, and boom! There was a yellow circle on the screen. Not very impressive, but it was a start. I wanted it to look more like a glowing sun, so I started playing around with different materials.
I swapped out the MeshBasicMaterial
for a MeshPhongMaterial
. This material reacts to light, so I added a point light to the scene. I experimented with the light’s position and intensity to get the shading on the sun looking right.
It was getting better, but it still felt flat. I remembered reading about shaders, which are little programs that run on the GPU and control how things are rendered. I decided to try using a custom shader to create a more realistic sun effect.
I found some example shaders online for creating a fiery, animated surface. I won’t lie, this part was tough. I spent a good chunk of time tweaking the shader code, trying to understand how it worked and how to modify it to get the look I wanted. Fragment shaders, vertex shaders…it was a lot to take in.
After a lot of trial and error, I finally had something that resembled a glowing, pulsating sun. It wasn’t perfect, but it was way cooler than that initial yellow circle.
Finally, added animation, so it can auto rotate the sun. I added code inside requestAnimationFrame().
All in all, it was a fun little project. I definitely learned a lot about shaders and how to create more complex visual effects with *. It’s amazing how much you can do with just a few lines of code (and a whole lot of patience!).