Create a 3D Heart for Valentine's Day With Three.js

Recently (depending on your time zone, I guess), it was Valentine’s Day season. Whether you wish to open your heart to someone special or simply spread love around the world, there is probably no better way than doing so with JavaScript!
This tutorial will show how we can use the three.js library to define and modify a custom 3D model and render it in the browser.
First, we will briefly cover what three.js is and why we will use it here.
Then we’ll get into the technical details and see how to create a scene, build and render a custom model, control the camera to admire it in all its glory, and finally, how to trigger a simple animation.
Ready to upgrade your basic emoji? ❤
Why Three.js
three.js is a JavaScript 3D library that relies on WebGL, an API to render 2D and 3D models in the browser.
When drawing in a regular HTML canvas and using the GPU to handle the rendering process, three.js allows the manipulation of 3D models straightforwardly and efficiently. Even NASA used it to simulate their rover landing on Mars.
Although it would have been completely feasible to create our heart only using the tools given by WebGL, you will see that three.js offers a rich API that makes our work much simpler.
Note: three.js also provides Canvas 2D, SVG, and CSS3D renderers, but we will stick to the WebGL one in this example.
There are different ways of installing three.js, but we will load it via a CDN this time. We can create a classic index.html file and load the library from it inside it with a script tag.
We will then work inside a heart.js file. At this point, nothing else is required. The canvas element will be added to the body automatically by the script.
<html>
<head>
<meta charset="utf-8">
<title>in my heart</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r124/three.min.js"></script>
<script src="./heart.js"></script>
</body>
</html>
Enter the Scene
Before working on the actual model, we will create a welcoming environment for it.
Placing your work of art in the right scenery is the least you can do. Thankfully, we can use the three.js tools we’re getting.
Let’s begin with our first function:
First, we need to define an actual scene object, which will hold nearly everything we will render. Big responsibilities, but it is a one-liner.
Then we will also need to create a camera object. It represents the point from where you can see the scene. Three.js provides different types of cameras, but this one fits our situation well.
As stated in the documentation:
“This projection mode is designed to mimic the way the human eye sees. It is the most common projection mode used for rendering a 3D scene.”
All right then. You can set your preferred configuration for this camera following the guidelines of the doc. Note that the second parameter is used for the camera aspect ratio, which is why it is computed from the window size here.
camera.position.z = 30
We also need to place the camera further from where we will put our shape.
const renderer = new THREE.WebGLRenderer({ antialias: true })
Now, we can instantiate our WebGLRenderer. You can decide to set antialias to true or not.
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
We set the size to match the windows and append the canvas to the body.
const color = 0xFFFFFF
const intensity = 0.75
const light = new THREE.PointLight(color, intensity)
light.position.set(-15, -10, 30)
scene.add(light)
Finally, we will add a light source to our scene. Three.js also provides different kinds of lights. I chose PointLight here since it is rather easy to visualize. It behaves like a light bulb — without any direction or anything.
Let’s call this createScene function inside an init method, which will be the entry point for our program.
function init () {
const {scene, camera, renderer} = createScene()
}
init()
Make the Heart
Now that we have our scene, we can finally start working on the star… hmm, the heart of the show! Since we are using a WebGL renderer, we know we can draw triangles easily with points (or vertices) coordinates.
First, we will define those coordinates; then we will see how we can draw triangles between them all.
Coordinates
We need to define a set of vertices for our model. Consider these the points that will be connecting every edge of your shape. In three.js, they can be configured using the Vector3 object. The positions we will pick can be completely arbitrary. I figured them out by drawing my model on a paper sheet, but I will cheat here and show you the coordinates I picked with pictures of the finished model.

You can see that each point has three coordinates in an (x, y, z) space, it is thicker in the middle, and the surrounding edges are all on the z=0 plane. Let me show you how it would look from another angle:

We will need another set of points for the other side, but they are symmetrical from the first one, so I will spare you a new screenshot.
Now, we want to render a surface between those points. You may have already noticed that every flat surface on our final model is a triangle. The triangle shape is the simplest you can draw if you have three points in a space, and it is widely used in 3D rendering as the fundamental piece of any model.
We are trying to keep it easy to visualize here, so we are only using a few triangles, but if you want to create a smoother shape, you can use many more.
Triangles
All right, we have coordinates, but we need to tell three.js where the triangles are that we want to display. The method we will use here is to store the indexes of those coordinates so that every group of three indexes represents a triangle.
Now, it’s time to look at our second function. Here’s what it looks like:
The first array (vertices) represents all the points that will shape our model, from 0 to 17. The second one (triangleIndexes) represents all the triangles we want to draw based on those points. It is just an array of integers, which are the indexes of the vertices in the first array.
The point is that for every three indexes, we can form a triangle with the three corresponding points of the first array. The first triangle in the figure corresponds to the points A, B, and C mentioned above.
Creating the mesh
With this data, we will now be able to draw something! Although we could completely ask three.js to draw the triangles without any link to each other, it would be much nicer to have a single object referencing our model.
In three.js, it is called a mesh.
To instantiate a new mesh, we still need to create two objects: a geometry and a material.
Think of the geometry as the reference of the shape and the material as the reference for the texture or fabric of your shape.
With that done, we will need one more function:
Let’s analyse what is going on here. First, we create a default geometry. No need for further configuration since we will assign it all of its faces.
for (let i in trianglesIndexes) {
if ((i+1)%3 === 0) {
geo.vertices.push(coordinatesList[trianglesIndexes[i-2]], coordinatesList[trianglesIndexes[i-1]], coordinatesList[trianglesIndexes[i]])
geo.faces.push(new THREE.Face3(i-2, i-1, i))
}
}
With this loop, we will iterate through the triangleIndexes array, and for every three indexes, we can store the corresponding vertice and the two previous ones with it.
Now that our geometry has those three vertices, we can also add a face to it. A Face3 object in three.js is defined by three indexes of vertices. We already made the work of matching our points and triangles (or should we say faces now), so it graciously is the same indexes we used to add the vertices to the geometry.
On a sidenote, default, three.js only renders the front side of a face at a time. It is defined by the order of the indexes, so if it does not work for you, maybe you need to change that order.
It is possible to render both sides if you need to, by configuring your material.
Now that we settled our geometry, we can create a material, as shown below:
geo.computeVertexNormals()
const material = new THREE.MeshPhongMaterial( { color: 0xad0c00 } )
We will use a specific material that can render light reflection (because why not), so we will need to call computeVertexNormals before that. And we configure the material with a nice deep red color.
All right, let’s add it to the init function, shown below:
function init () {
const {scene, camera, renderer} = createScene()
const { vertices, trianglesIndexes} = useCoordinates()
const { geo, material, heartMesh } = createHeartMesh(vertices, trianglesIndexes)
}
It is not yet enough to be able to contemplate the result of our efforts, but we’ll soon be talking about the rendering of the scene. Let’s add a final touch before that.
Wireframe
Now that we can see it floating in the air, we want to add an effect that will separate every face. This is not just to make it super stylish but also to understand better how our triangles are displayed on our model.
The object rendering the edges of the mesh’s faces is called a wireframe, and once we know how to create a mesh, it is pretty easy.
We can automatically create a WireframeGeometry from the first geometry we created before and create our wireframe using the right material and line object.
Finally, we can add it to our heart mesh.
Well, everything seems to be on point. Let’s try to render something!
Putting the Model in the Scene
scene.add(heartMesh)
Done! What’s next?
More seriously, if it is this easy to add our mesh to the scene, we also need to see how we can render it and apply modifications to it.
Rendering
Rendering is simple enough since we instantiated a renderer object and have everything we need.
However, especially if we want to animate our model, we will call a new render regularly. Nowadays, the usual frequency for smooth movement is sixty frames per second.
We could simply use a setInterval and set it to a sixtieth of a second, but browsers provide a function to get the same effect without relying as much on the main thread: requestAnimationFrame.
const animate = function () {
requestAnimationFrame( animate )
renderer.render( scene, camera )
heartMesh.rotation.y -= 0.005
}
animate()
requestAnimationFrame receives a callback as its argument and will call it for each available frame. You can read more about it on the MDN doc.
heartMesh.rotation.y -= 0.005
With this behaviour, we can manage a simple modification of our model. By decrementing (or incrementing) the rotation of the mesh, we can make it rotate around the desired axis.
The higher the value of the increment, the faster the effect.
Let’s try to call all this in the init function.
If you made it this far, you now have a nice 3D model of a heart rotating around itself, and you are pretty much ready to open your heart to everyone around you. Congratulations!
Now, if you think you can handle a little more, we can add a more complex animation and see how it can be triggered with the user input.
Beating animation
Let us bring our model to life with another animation.
We will use what we learned with the rotating animation, but in a way that makes it seem like our heart is beating.
You know the drill. Let’s write another function:
What we want to perform here is to scale up the mesh and then scale it back down to its original value. To make the transformation uniform, we should add the same increment value to the three axes of the mesh’s scale attribute.
We can settle on a max value, and from there, we can scale down once it is reached. I took 1.4, but feel free to make it bigger or smaller for a more subtle animation.
Then our algorithm is pretty simple: we are going to add the beatingIncrement to each of the scale properties, and once we exceed our maximum value, we toggle a boolean flag and then subtract the increment value from the scale properties.
This function is going to be called multiple times by the animate function we defined earlier, so although it looks like the kind of code one could write inside a while loop, iterations are triggered by the recursive way of rendering the scene.
Let’s add the beating function to the animate body with the following code:
const animate = function () {
requestAnimationFrame( animate )
renderer.render( scene, camera )
heartMesh.rotation.y -= 0.005
beatingAnimation(heartMesh)
}
Wonderful! We have a pulse!
Let’s keep it going and let the user decide when the heart should beat.
Interactivity
Our model is proudly standing in our scene, even moving on its own, but if you stick with me a little more, we can see how we can handle user interactions.
First, we will use ray casting to understand how to deal with click events on the canvas. Afterward, we will set up camera controls, which are more than useful tools in the world of 3D modeling.
Handling user input with Raycaster
Usually, the raycaster class handles user interaction by making the intersection between the mouse pointer and 3D models exploitable.
Here we go. Here’s some more code:
This function needs a reference to the camera, the scene, and a unique mesh ID that will interact with the pointer. It returns a function, which will be called on the click/touch event.
This handler method sets the coordinates of the mouse object and allows the raycaster to find out which meshes intercept the pointer.
if (intersects.length && intersects[0].object.uuid === meshUuid) {
startAnim = true
}
After that, we only have to test if the first intersected object’s id matches the one passed in the parameters.
It has to be the first, or else it would mean it is hidden behind some other mesh. In this case, we can toggle our flag variable.
This variable can trigger our beating animation in the animate function.
const animate = function () {
requestAnimationFrame( animate )
renderer.render( scene, camera )
heartMesh.rotation.y -= 0.005
startAnim && beatingAnimation(heartMesh)
}
and toggle back to false when the animation is over.
We need to modify the beatingAnimation function. Here’s how to do that:
function beatingAnimation (mesh) {
// [...]
if (mesh.scale.x <= 1) {
scaleThreshold = false
startAnim = false // we must stop it right here or it will start over again
}
}
We can call handleMouseIntersection from the init function, and then hook the event handler it returns to the click listener of the window object.
Wonderful! You now gained control over the beating! In hindsight, that sounds like a big responsibility.
Controls
You can be proud. Your model is in front of you, and you gained control over its animations, but how about we push it a little further one last time and set up controls so you can admire it from all angles?
Sounds fun, right? Let’s try to add orbit controls first and then use the device orientation API for mobile users.
Orbit controls
Orbit controls allow you to make the camera orbit around a target. This means we can move the camera further and closer to the point it’s located and rotate the camera around this point while still being oriented toward the target.
This lets us change the angle and point of view.
Although this is not natively supported by three.js, there is an API we can use to set up those controls. See the doc here.
We can add this new dependency with a script tag in index.html.
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
We now have access to its constructor through the THREE object. Let’s instantiate it inside a dedicated function.
function setControls (camera, domElement) {
const controls = new THREE.OrbitControls( camera, domElement )
controls.update()
}
We can call it in the init function, and that’s it! You can now orbit around your heart by holding a left click, zoom in and out with the scroll wheel, and even move the camera with a right click (or their equivalent on a trackpad or a touchscreen).
Note that it is possible to restrain the range of the camera moves; this can be useful.
These actions are already more than enough to admire your creation, but when using a mobile device, you can also take advantage of the device orientation to transpose a physical movement into a camera one.
Device Orientation Controls
Like orbit controls, there is a non-native API we can use, and you can read more about it here.
Contrary to the orbit one, it can only change the camera orientation, so you can pretend your phone is a window to the parallel universe where your heart resides and beats.
The code for DeviceOrientationControls can be found on the three.js GitHub repository in the example section, but it is referencing a build folder we do not have in our project. You can use this one I adapted for a more standalone version or make your own. Just make sure to reference it in your index.html file.
Once it is done, we can use it in our previous function. It would be pleasant not to delete what we just did, so let’s make the controls’ initialisation more conditional.
We need to return the controls reference this time because when using the DeviceOrientationControls, we have to call controls.update() inside the rendering loop as well.
const animate = function () {
requestAnimationFrame( animate )
renderer.render( scene, camera )
heartMesh.rotation.y -= 0.005
startAnim && beatingAnimation(heartMesh)
controls.update() // this line is new
}
animate()
Now you can easily switch between the two control modes by changing the parameter in the setControls call. It would not be hard to link it to user input, among other ideas.
const { controls } = setControls(camera, renderer.domElement, true)
There may be a way to combine both controls into one and gain full power upon the camera, but I haven’t found out about it at the time I am writing this, and I guess it could become a little messy.
Congratulations!
If you made it this far, you now have built a wonderful pulsating on-command 3D heart!
We went through the initialisation and use of the three.js API to create a scene and render meshes inside of it, but we also used a coordinate system to build an entire model from the ground up.
Lastly, we handled user interactions with the canvas and let them control the camera object.
You can find the source code here and a live demo here.
You can also check out the advanced version, which features a couple more details, i.e., control limitations, wall models surrounding the heart, and user input to let you pick your controls when loading the page.
If you are interested in diving deeper into 3D rendering, I highly recommend this guide by Maxime Euzière.
This was written after I did this experiment. I am more of a beginner than an expert, so if you spot something that could be improved and shared with the other readers, please feel free to let me know!
Hopefully, you learned something from my experience. Thank you for reading!