Skip to content
ImagineWorld

Exploring Advanced Geometries

node_idnode-book_learn-three-js_chapter-06-exploring-advanced-geometries
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleExploring Advanced Geometries
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6 — Exploring Advanced Geometries

Section titled “Chapter 6 — Exploring Advanced Geometries”

In Chapter 5, Learning to Work with Geometries, we showed you all the basic geometries provided by Three.js. Besides these basic geometries, Three.js also offers a set of more advanced and specialized objects.

In this chapter, we’ll show you these advanced geometries:

  • How to use advanced geometries such as THREE.ConvexGeometry, THREE.LatheGeometry, THREE.BoxLineGeometry, THREE.RoundeBoxGeometry, THREE.TeapotGeometry, and THREE.TubeGeometry.
  • How to create 3D shapes from 2D shapes using THREE.ExtrudeGeometry. We’ll create a 3D shape from a 2D SVG image, and we will extrude from 2D Three.js shapes to create novel 3D shapes.
  • If you want to create custom shapes yourself, you can continue playing with the ones we’ve discussed in the previous chapters. Three.js, however, also offers a THREE.ParametricGeometry object. With parametric geometry, you can create geometry with parameters you can change to effect the shape of the geometry.
  • We’ll also show how you can create 3D text effects using THREE.TextGeometry, and show you how to use the Troika library for when you want to add 2D text labels to your scene.
  • Additionally, we’ll show you how you can use two helper geometries, THREE.WireframeGeometry and THREE.EdgesGeometry. These helpers allow you to see more details about other geometries.

We’ll start with the first one from this list, THREE.ConvexGeometry.

In this section, we’ll look at a number of advanced Three.js geometries. We will start with THREE.ConvexGeometry, which you can use to create convex hulls.

With THREE.ConvexGeometry, we can create a convex hull from a set of points. A convex hull is the minimal shape that encompasses all these points. The easiest way to understand this is by looking at an example. If you open up the convex-geometry.html example, you’ll see the convex hull for a random set of points. The following screenshot shows this geometry:

Figure 6.1 – The convex hull encompassing all the points

In this example, we generate a random set of points, and based on these points, we create THREE.ConvexGeometry. In the example, you can use the redraw button in the menu on the right, which will generate 20 new points and draw the convex hull. If you try this for yourself, enable the material’s transparency and set the opacity to a level below 1 to see the points that are used to create this geometry. These points are created as small THREE.SphereGeometry objects for this example.

To create THREE.ConvexGeometry, we need a set of points. The following code fragment shows how we do this:

const generatePoints = () => {
const spGroup = new THREE.Object3D()
spGroup.name = 'spGroup'
const points = []
for (let i = 0; i < 20; i++) {
const randomX = -5 + Math.round(Math.random() * 10)
const randomY = -5 + Math.round(Math.random() * 10)
const randomZ = -5 + Math.round(Math.random() * 10)
points.push(new THREE.Vector3(randomX, randomY, randomZ))
}
const material = new THREE.MeshBasicMaterial({ color:
0xff0000, transparent: false })
points.forEach(function (point) {
const spGeom = new THREE.SphereGeometry(0.04)
const spMesh = new THREE.Mesh(spGeom, material)
spMesh.position.copy(point)
spGroup.add(spMesh)
})
return {
spGroup,
points
}
}

As you can see in this snippet of code, we create 20 random points (THREE.Vector3), which we push into an array. Next, we iterate this array and create THREE.SphereGeometry, whose position we set to one of these points (position.copy(point)). All the points are added to a group, so we can easily replace them once we do a redraw. Once you have this set of points, creating a THREE.ConvexGeometry from them is very easy, as shown in the following code snippet:

const convexGeometry = new THREE.ConvexGeometry(points);

An array containing vertices (of the THREE.Vector3 type) is the only argument THREE.ConvexGeometry takes. Note that if you want to render a smooth THREE.ConvexGeometry, you should call computeVertexNormals, as we explained in Chapter 2, The Basic Components that Make up a Three.js Application.

The next complex geometry is THREE.LatheGeometry, which, for example, can be used to create vase-like shapes.

THREE.LatheGeometry allows you to create shapes from a set of points that together form a curve. If you look at Figure 6*.2*, you can see that we created a number of points (the red dots), which Three.js uses to create THREE.LatheGeometry. Once again, the easiest way to understand what THREE.LatheGeometry looks like is by looking at an example. This geometry is shown in lathe-geometry.html. The following screenshot taken from the example shows this geometry:

Figure 6.2 – A lathe for vase-like meshes

In the preceding screenshot, you can see the points used to create this geometry as a set of small red spheres. The positions of these points are passed into THREE.LatheGeometry, together with arguments that define the shape of the geometry. Before we look at all the arguments, let’s look at the code used to create the individual points and how THREE.LatheGeometry uses these points:

const generatePoints = () => {
...
const points = []
const height = 0.4
const count = 25
for (let i = 0; i < count; i++) {
points.push(new THREE.Vector3((Math.sin(i * 0.4) +
Math.cos(i * 0.4)) * height + 3, i / 6, 0))
}
...
}
// use the same points to create a LatheGeometry
const latheGeometry = new THREE.LatheGeometry (points,
segments, phiStart, phiLength);
latheMesh = createMesh(latheGeometry);
scene.add(latheMesh);
}

In this piece of JavaScript, we can see that we generate 25 points whose x coordinate is based on a combination of sine and cosine functions, while the y coordinate is based on the i and count variables. This creates a spline visualized by the red dots in the preceding screenshot. Based on these points, we can create THREE.LatheGeometry. Besides the array of vertices, THREE.LatheGeometry takes a couple of other arguments. The following list explains these properties:

  • points: These are the points that make up the spline used to generate the bell/vase shape.
  • segments: These are the number of segments used when creating the shape. The higher this number, the more round and smooth the resulting shape will be. The default value for this is 12.
  • phiStart: This determines where to start on a circle when generating the shape. This can range from 0 to 2*PI. The default value is 0.
  • phiLength: This defines how fully generated the shape is. For instance, a quarter shape will be 0.5*PI. The default value is the full 360 degrees or 2*PI. This shape will start at the position of the phiStart property.

In Chapter 5, we’ve already seen BoxGeometry. Three.js also provides two other box-like geometries, which we’ll discuss next.

If you just want to show the outline, you can use THREE.BoxLineGeometry. This geometry works exactly like THREE.BoxGeometry, but instead of rendering a solid object, it renders the box using lines like this (from box-line-geometry.html):

Figure 6.3 – A box rendered using lines

You use this geometry in the same way as THREE.BoxGeometry, but instead of creating THREE.Mesh, we need to create THREE.LineSegments, using one of the available line-specific materials:

import { BoxLineGeometry } from 'three/examples/jsm/
geometries/BoxLineGeometry'
const material = new THREE.LineBasicMaterial({ color:
0x000000 }),
const geometry = new BoxLineGeometry(width, height, depth,
widthSegments, heightSegments, depthSegments)
const lines = new THREE.LineSegments(geometry, material)
scene.add(lines)

For an explanation of the properties you can pass into this geometry, refer to the THREE.BoxGeometry section of Chapter 5.

Three.js also provides a slightly more advanced THREE.BoxGeometry, where you can have nicely rounded corners. You can do this with RoundedBoxGeometry.

This geometry uses the same properties as THREE.BoxGeometry, but it also allows you to specify how round the corners should be. In the rounded-box-geometry example, you can see how this looks:

Figure 6.4 – A box with rounded corners

For this geometry, we can specify the dimensions of the box by specifying width, height, and depth. Besides these properties, this geometry provides two additional ones:

  • radius: This is the size of the rounded corners. The higher this value, the more rounded the corners will be.
  • segments: This property defines how detailed the corners will be. If this is set to a low value, Three.js will use fewer vertices for the definition of the rounded corners.

Before we move on to showing how you can create 3D geometries from a 2D object, we’ll look at the final geometry provided by Three.js, TeapotGeometry.

TeapotGeometry is a geometry that you can use to render, not very surprisingly, a teapot. This teapot is a standard reference model for 3D renders and has been used since 1975. More information on the history of this model can be found here: https://www.computerhistory.org/revolution/computer-graphics-music-and-art/15/206.

Using this model works in exactly the same way as all the other models we’ve seen so far:

import { TeapotGeometry } from 'three/examples/jsm/
geometries/TeapotGeometry'
...
const geom = new TeapotGeometry(size, segments, bottom,
lid, body, fitLid, blinn)

You specify the specific properties and then create the geometry, which you assign to THREE.Mesh. The result, depending on the properties, looks like this (in the teapot-geometry.html example):

Figure 6.5 – The Utah teapot

To configure this geometry, you can use the following properties:

  • size: This is the size of the teapot.
  • segments: This defines how many segments are used to create the wireframe of this teapot. The more segments you use, the more smooth the teapot will look.
  • bottom: If set to true, the bottom of the teapot will be rendered. If false, the bottom won’t be rendered, which you could use when the teapot is located on a surface and there is no need to render the bottom of it.
  • lid: If set to true, the lid of the teapot will be rendered. If false, the lid won’t be rendered.
  • body: If set to true, the body of the teapot will be rendered. If false, the body won’t be rendered.
  • fitLid: If set to true, the lid will exactly fit the teapot. If false, there will be a small space between the lid and the body of the teapot.
  • blinn: This defines whether to use the same aspect ratio of the teapot as the original 1975 model this teapot is based on.

In the next sections, we’ll look at an alternative way of creating geometries by extracting a 3D geometry from a 2D shape.

Creating a geometry by extruding a 2D shape

Section titled “Creating a geometry by extruding a 2D shape”

Three.js provides a way in which we can extrude a 2D shape into a 3D shape. By extruding, we mean stretching out a 2D shape along its z axis to convert it to 3D. For instance, if we extrude THREE.CircleGeometry, we get a shape that looks like a cylinder, and if we extrude THREE.PlaneGeometry, we get a cube-like shape. The most versatile way of extruding a shape is using THREE.ExtrudeGeometry.

With THREE.ExtrudeGeometry, you can create a 3D object from a 2D shape. Before we dive into the details of this geometry, let’s first look at an example, extrude-geometry.html. The following screenshot taken from the example shows this geometry:

Figure 6.6 – Creating a 3D geometry from a 2D shape

In this example, we took the 2D shape we created in the 2D geometries section in Chapter 5, and used THREE.ExtrudeGeometry to convert it to 3D. As you can see in the preceding screenshot, the shape is extruded along the z axis, which results in a 3D shape. The code to create THREE.ExtrudeGeometry is very easy:

const geometry = new THREE.ExtrudeGeometry(drawShape(), {
curveSegments,
steps,
depth,
bevelEnabled,
bevelThickness,
bevelSize,
bevelOffset,
bevelSegments,
amount
})

In this code, we created the shape with the drawShape() function, just as we did in Chapter 5. This shape is passed on to the THREE.ExtrudeGeometry constructor together with a set of properties. With these properties, you can define exactly how the shape should be extruded. The following list explains the options you can pass into THREE.ExtrudeGeometry:

  • shapes: One or more shapes (THREE.Shape objects) are required to extrude the geometry. See Chapter 5, on how to create such a shape.
  • depth: This determines how far the shape should be extruded (the depth). The default value is 100.
  • bevelThickness: This determines the depth of the bevel. The bevel is the rounded corner between the front and back faces and the extrusion. This value defines how deep into the shape the bevel goes. The default value is 6.
  • bevelSize: This determines the height of the bevel. This is added to the normal height of the shape. The default value is bevelThickness - 2.
  • bevelSegments: This defines the number of segments that will be used by the bevel. The more the number of segments used, the smoother the bevel will look. The default value is 3. Note that if you add more segments, you’re also increasing the vertex count, which could have an adverse effect on performance.
  • bevelEnabled: If this is set to true, a bevel is added. The default value is true.
  • bevelOffset: The distance from the outline of the shape where the bevel starts. The default value is 0.
  • curveSegments: This determines how many segments will be used when extruding the curves of shapes. The higher the number of segments used, the smoother the curves will look. The default value is 12.
  • steps: This defines the number of segments the shape will be divided into along the extrusion depth. The default value is 1, which means it will have a single segment along its depth, without unnecessary additional vertices.
  • extrudePath: This is the path (THREE.CurvePath) along which the shape should be extruded. If this isn’t specified, the shape is extruded along the z axis. Note that if you’ve got a curving path, you also need to make sure to set a higher value for the steps property so that it can follow the curve accurately.
  • uvGenerator: When you use a texture with your material, the UV mapping determines what part of a texture is used for a specific face. With the uvGenerator property, you can pass in your own object, which will create the UV settings for the faces that are created for the passed-in shapes. More information on UV settings can be found in Chapter 10, Loading and Working with Textures. If nothing is specified, THREE.ExtrudeGeometry.WorldUVGenerator is used.

If you want to use a different material for the faces and the sides, you can pass in an array of materials to THREE.Mesh. The first material passed in will be applied to the face, and the second material will be used for the sides. You can experiment with these options using the menu from the extrude-geometry.html example. In this example, we extruded the shape along its z axis. As you can see in the options listed earlier in this section, you can also extrude a shape along a path with the extrudePath option. In the following geometry, THREE.TubeGeometry, we’ll do just that.

THREE.TubeGeometry creates a tube that extrudes along a 3D spline. You specify the path using a number of vertices, and THREE.TubeGeometry will create the tube. An example that you can experiment with can be found in the sources for this chapter (tube-geometry.html). The following screenshot shows this example:

Figure 6.7 – TubeGeometry based on random 3D vertices

As you can see in this example, we generate a number of random points and use those points to draw the tube. With the controls in the menu, we can define how the tube looks. The code needed to create a tube is very simple, as follows:

const points = ... // array of THREE.Vector3 objects
const tubeGeometry = new TubeGeometry(
new THREE.CatmullRomCurve3(points),
tubularSegments,
radius,
radiusSegments,
closed
)

What we need to do first is get a set of vertices (the points variable) of the THREE.Vector3 type, just like we did for THREE.ConvexGeometry and THREE.LatheGeometry. Before we can use these points, however, to create the tube, we first need to convert these points to THREE.Curve. In other words, we need to define a smooth curve through the points we defined. We can do this simply by passing in the array of vertices to the constructor of THREE.CatmullRomCurve3, or any of the other Curve implementations provided by Three.js. With this curve and the other arguments (which we’ll explain in this section), we can create the tube and add it to the scene.

In this example, we’ve used THREE.CatmullRomCurve3. Three.js provides a number of other curves you can use as well that take slightly different arguments, but they can be used to create different curve implementations. Out of the box, Three.js comes with the following curves: ArcCurve, CatmullRomCurve3,CubicBezierCurve,Cub icBezierCurve3,EllipseCurve,LineCurve,LineCurve3,QuadraticBezierCurve,
QuadraticBezierCurve3, and SplineCurve.

THREE.TubeGeometry takes some other arguments besides the curve. The following lists all the arguments for THREE.TubeGeometry:

  • path: This is THREE.SplineCurve3, which describes the path this tube should follow.
  • tubularSegments: These are the segments used to build up the tube. The default value is 64. The longer the path, the more segments you should specify.
  • radius: This is the radius of the tube. The default value is 1.
  • radiusSegments: This is the number of segments to be used along the length of the tube. The default value is 8. The more you use, the more round the tube will look.
  • closed: If this is set to true, the start and the end of the tube will be connected. The default value is false.

The last extrude example we’ll show in this chapter isn’t really a different type of geometry, but we’ll use THREE.ExtrudeGeometry to create extrusions from an SVG image.

What is SVG?

SVG is an XML-based standard that can be used to create vector-based 2D images for the web. This is an open standard that is supported by all modern browsers. Directly working with SVG and manipulating it from JavaScript, however, isn’t very straightforward. Luckily, there are a couple of open source JavaScript libraries that make working with SVG a lot easier. Paper.js, Snap.js, D3.js, and Raphael.js are some of the best. If you want a graphical editor, you can also use the open source Inkscape product.

When we discussed THREE.ShapeGeometry in Chapter 5, we mentioned that SVG follows pretty much the same approach to drawing shapes. In this section, we’ll look at how you can use SVG images together with THREE.SVGLoader to extrude SVG images. We’ll use the Batman logo as an example:

Figure 6.8 – The Batman SVG base image

First, let’s look at what the original SVG code looks like (you can also see this for yourself when looking at the source code of the assets/svg/batman.svg file):

<svg version="1.0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1152px" height="1152px" xml:space="preserve">
<g>
<path id="batman-path" style="fill:rgb(0,0,0);" d="M 261.135 114.535 C 254.906 116.662 247.491 118.825 244.659 119.344 C
229.433 122.131 177.907 142.565 151.973 156.101 C 111.417
177.269 78.9808 203.399 49.2992 238.815 C 41.0479 248.66
26.5057 277.248 21.0148 294.418 C 14.873 313.624 15.3588
357.341 21.9304 376.806 C 29.244 398.469 39.6107 416.935
52.0865 430.524 C 58.2431 437.23 63.3085 443.321 63.3431
444.06 ... 261.135 114.535 "/>
</g>
</svg>

Unless you’re an SVG guru, this probably won’t mean too much to you. Basically though, what you see here is a set of drawing instructions. For instance, C 277.987 119.348 279.673 116.786 279.673 115.867 tells the browser to draw a cubic Bezier curve, and L 489.242 111.787 tells us that we should draw a line to that specific position. Luckily though, we won’t have to write the code to interpret this ourselves and can use THREE.SVGLoader instead, as you can see in the following code:

// returns a promise
const batmanShapesPromise = new SVGLoader().loadAsync('/assets/svg/batman.svg')
// when promise resolves the svg will contain the shapes
batmanShapes.then((svg) => {
const shapes = SVGLoader.createShapes(svg.paths[0])
// based on the shapes we can create an extrude geometry
as we've seen earlier
const geometry = new THREE.ExtrudeGeometry(shapes, {
curveSegments,
steps,
depth,
bevelEnabled,
bevelThickness,
bevelSize,
bevelOffset,
bevelSegments,
amount
})
...
}

In this code fragment, you can see that we use SVGLoader to load the SVG file. We use loadAsync here, which will return a JavaScript Promise. When that Promise resolves, we get access to the loaded svg data. This data can contain a list of path elements, each representing the path element of the original SVG. In our example, we’ve only got one, so we use svg.paths[0] and pass it into SVGLoader.createShapes to convert it into an array of THREE.Shape objects. Now that we’ve got the shapes, we can use the same approach we used earlier when we extruded our custom-created 2D geometry and use THREE.ExtrudeGeometry to create a 3D model from the 2D-loaded SVG shapes.

The final result can be seen when you open the extrude-svg.html example in the browser:

Figure 6.9 – A 3D-created Batman logo extruded from a 2D SVG image

The last geometry we’ll discuss in this section is THREE.ParametricGeometry. With this geometry, you can specify a couple of functions that are used to programmatically create geometries.

With THREE.ParametricGeometry, you can create a geometry based on an equation. Before we dive into our own example, a good thing to start with is to look at the examples already provided by Three.js. When you download the Three.js distribution, you get the examples/js/ParametricGeometries.js file. In this file, you can find a couple of examples of equations you can use together with THREE.ParametricGeometry.

The most basic example is the function to create a plane:

plane: function ( width, height ) {
return function ( u, v, target ) {
const x = u * width;
const y = 0;
const z = v * height;
target.set( x, y, z );
};
},

This function is called by THREE.ParametricGeometry. The u and v values will range from 0 to 1 and will be called a large number of times, for all the values from 0 to 1. In this example, the u value is used to determine the x coordinate of the vector, and the v value is used to determine the z coordinate. When this is run, you’ll have a basic plane with a width of width and a depth of depth.

In our example, we do something similar. However, instead of creating a flat plane, we create a wave-like pattern, as you can see in the parametric-geometry.html example. The following screenshot shows this example:

Figure 6.10 – A wave-like plane using a parametric geometry

To create this shape, we passed the following function to THREE.ParametricGeometry:

const radialWave = (u, v, optionalTarget) => {
var result = optionalTarget || new THREE.Vector3()
var r = 20
var x = Math.sin(u) * r
var z = Math.sin(v / 2) * 2 * r + -10
var y = Math.sin(u * 4 * Math.PI) + Math.cos(v * 2 *
Math.PI)
return result.set(x, y, z)
}
const geom = new THREE.ParametricGeometry(radialWave, 120,
120);

As you can see in this example, with a few lines of code, we can create some really interesting geometries. In this example, you can also see the arguments we can pass to THREE.ParametricGeometry:

  • function: This is the function that defines the position of each vertex based on the u and v values provided
  • slices: This defines the number of parts the u value should be divided into
  • stacks: This defines the number of parts the v value should be divided into

By changing the function, we can easily use the exact same approach to render a completely different object:

Figure 6.11 – A Klein bottle rendered using a parametric geometry

Here’s a final note on how to use the slices and stacks properties before moving on to the next part of this chapter. We mentioned that the u and v properties are passed into the function argument provided and that the values of these two properties range from 0 to 1. With the slices and stacks properties, we can define how often the passed-in function is called. If, for instance, we set slices to 5 and stacks to 4, the function will be called with the following values:

u:0/5, v:0/4
u:1/5, v:0/4
u:2/5, v:0/4
u:3/5, v:0/4
u:4/5, v:0/4
u:5/5, v:0/4
u:0/5, v:1/4
u:1/5, v:1/4
...
u:5/5, v:3/4
u:5/5, v:4/4

So, the higher these values are, the more vertices you get to specify and the smoother your created geometry will be. You can use the menu at the right of the parametric-geometry.html example to see this effect.

For more examples, you can look at the examples/js/ParametricGeometries.js file in the Three.js distribution. This file contains functions to create the following geometries:

  • Klein bottle
  • Plane
  • Flat Mobius strip
  • 3D Mobius strip
  • Tube
  • Torus knot
  • Sphere
  • Plane

Sometimes, you need to see more details about your geometry, and you don’t care too much about materials and how the mesh will be rendered. If you want to look at the vertices and the faces, or even just the outline, Three.js provides a couple of geometries that can help you with this (besides enabling the wireframe property of the material you use for the mesh). We’ll explore these in the following section.

Three.js comes with two helper geometries out of the box that make it easier to see the details or just the outline of a geometry:

  • THREE.EdgesGeometry, which provides a geometry that only renders the edges of a geometry
  • THREE.WireFrameGeometry, which renders just the geometry without showing any faces

First, let’s look at THREE.EdgesGeometry.

With THREE.EdgesGeometry, you wrap an existing geometry, which is then rendered by just showing the edges and not the individual vertices and faces. An example of this is shown in the edges-geometry.html example:

Figure 6.12 – EdgesGeometry only showing the edges, not the individual faces

In the previous screenshot, you can see that the outline of RoundedBoxGeometry is shown, where we just see the edges. Since RoundedBoxGeometry has smooth corners, those are shown when using THREE.EdgesGeometry.

To use this geometry, you just wrap an existing geometry like this:

const baseGeometry = new RoundedBoxGeometry(3, 3, 3, 10, 0.4)
const edgesGeometry = THREE.EdgesGeometry(baseGeometry, 1.5)
}

The only property THREE.EdgesGeometry takes is thresholdAngle. With this property, you can determine when this geometry draws an edge. In edges-geometry.html, you can control this property to see the effect.

If you’ve got an existing geometry and want to see the wireframe, you can configure a material to show this wireframe:

const material = new THREE.MeshBasicMaterial({ color: 0xffff00, wireframe: true })

Three.js also provides a different way of using THREE.WireFrameGeometry.

This geometry simulates the behavior you see when you set the wireframe property of a material to true:

Figure 6.13 – Wireframe geometry showing all the individual faces of a geometry

Using this material works in the same way as using THREE.EdgesGeometry:

const baseGeometry = new THREE.TorusKnotBufferGeometry(3, 1, 100, 20, 6, 9)
const wireframeGeometry = new THREE.WireframeGeometry(baseGeometry)

This geometry doesn’t take any additional properties.

The last part of this chapter deals with creating 3D text objects. We’ll show you two different approaches, one with the THREE.Text object and one where we use an external library.

In this section, we’ll have a quick look at how you can create 3D text. First, we’ll look at how to render text using the fonts provided by Three.js, and how you can use your own fonts for this. Then, we’ll show a quick example of using an external library called Troika (https://github.com/protectwise/troika) that makes it really easy to create labels and 2D text elements and add them to your scene.

Rendering text in Three.js is very easy. All you have to do is define the font you want to use and use the same extrude properties we saw when we discussed THREE.ExtrudeGeometry. The following screenshot shows a text-geometry.html example of how to render text in Three.js:

Figure 6.14 – Rendering text in Three.js

The code required to create this 3D text is as follows:

import { FontLoader } from 'three/examples/jsm/
loaders/FontLoader'
import { TextGeometry } from 'three/examples/jsm/
geometries/TextGeometry'
...
new FontLoader()
.loadAsync('/assets/fonts/helvetiker_regular.typeface.json')
.then((font) => {
const textGeom = new TextGeometry('Some Text', {
font,
size,
height,
curveSegments,
bevelEnabled,
bevelThickness,
bevelSize,
bevelOffset,
bevelSegments,
amount
})
...
)

In this code fragment, you can see that we first have to load the font. For this, Three.js provides FontLoader(), where we provide the name of the font to load, just like we did with SVGLoader, where we get back a JavaScript Promise. Once that Promise resolves, we use the loaded font to create TextGeometry.

The options we can pass into THREE.TextGeometry match those that we can pass into THREE.ExtrudeGeometry:

  • font: The loaded font to use for the text.
  • size: This is the size of the text. The default value is 100.
  • height: This is the length (depth) of the extrusion. The default value is 50.
  • curveSegments: This defines the number of segments used when extruding the curves of shapes. The more segments there are, the smoother the curves will look. The default value is 4.
  • bevelEnabled: If this is set to true, a bevel is added. The default value is false.
  • bevelThickness: This is the depth of the bevel. The bevel is the rounded corner between the front and back faces and the extrusion. The default value is 10.
  • bevelSize: This is the height of the bevel. The default value is 8.
  • bevelSegments: This defines the number of segments that will be used by the bevel. The more segments there are, the smoother the bevel will look. The default value is 3.
  • bevelOffset: This is the distance from the outline of the shape where the bevel starts. The default value is 0.

Since THREE.TextGeometry is also THREE.ExtrudeGeometry, the same approach applies if you want to use a different material for the front and the sides of the material. If you pass in an array of two materials when creating THREE.Mesh, Three.js will apply the first material to the front and the back of the text, and the second one to the sides.

It’s also possible to use other fonts with this geometry, but you first need to convert them to JSON – how to do this is shown in the next section.

There are a couple of fonts provided by Three.js that you can use in your scenes. These fonts are based on the fonts provided by the TypeFace.js library. TypeFace.js is a library that can convert TrueType and OpenType fonts to JavaScript. The resulting JavaScript file or JSON file can be included in your page, and the font can then be used in Three.js. In older versions, the JavaScript file was used, but in later Three.js versions, Three.js switched to using the JSON file.

To convert an existing OpenType or TrueType font, you can use the web page at https://gero3.github.io/facetype.js/:

Figure 6.15 – Converting a font to a typeface-supported format

On this page, you can upload a font, and it will be converted to JSON for you. Note that this won’t work so well for all types of fonts. The simpler the font (more straight lines), the better the chance that it will be rendered correctly when used in Three.js. The resulting file looks like this, where each of the characters (or glyphs) is described:

{"glyphs":{"¦":{"x_min":359,"x_max":474,"ha":836,"o":"m 474 971 l 474 457 l
359 457 l 359 971 l 474 971 m 474 277 l 474 -237 l 359 -237 l 359 277 l 474
277 "},"Ž":{"x_min":106,"x_max":793,"ha":836,"o":"m 121 1013 l 778 1013 l
778 908 l 249 115 l 793 115 l 793 0 l 106 0 l 106 104 l 620 898 l 121 898 l
121 1013 m 353 1109 l 211 1289 l 305 1289 l 417 1168 l 530 1289 l 625 1289
l 482 1109 l 353 1109 "},"Á":{"x_min":25,"x_max":811,"ha":836,"o":"m 417
892 l 27 ....

Once you’ve got the JSON file, you can use FontLoader (as we showed previously in the Rendering text section) to load this font and assign it to the font property of the options you can pass into TextGeometry.

For the final example of this chapter, we’re going to look at a different way to create text with Three.js.

If you want to create labels or 2D text marks for certain parts of your scene, there is an alternative option to using the THREE.Text geometry. You can also use an external library called Troika: https://github.com/protectwise/troika.

This is a fairly big library that provides lots of functionalities to add interactivity to your scenes. For this example, we’ll only look at the text module of that library. An example of what we’re going to create is shown in the troika-text.html example:

Figure 6.16 – Troika text for 2D labels

To use this library, we first have to install it (if you followed the instructions from Chapter 1, Creating Your First 3D Scene with Three.js, you can already use this library): $ yarn add troika-three-text. Once installed, we can import it and use it just like we do with the rest of the modules provided by Three.js:

import { Text } from 'troika-three-text'
const troikaText = new Text()
troikaText.text = 'Text rendering with Troika!\nGreat for
2D labels'
troikaText.fontSize = 2
troikaText.position.x = -3
troikaText.color = 0xff00ff
troikaText.sync()
scene.add(troikaText)

In the previous code fragment, we showed how you can use Troika to create a simple text element. You only need to call the Text() constructor and set the properties. One thing to keep in mind, however, is that whenever you change a property in the Text() object, you have to call troikaText.sync(). That will make sure that the changes are also applied to the model rendered on the screen.

We saw a lot in this chapter. We introduced a couple of advanced geometries and showed you how you can create and render text elements with Three.js. We showed you how you can create really beautiful shapes using advanced geometries such as THREE.ConvexGeometry, THREE.TubeGeometry, and THREE.LatheGeometry and how can you experiment with these geometries to get the results you’re looking for. A very nice feature is that we can also convert existing SVG paths to Three.js using THREE.ExtrudeGeometry.

We’ve also quickly looked at a couple of geometries that are very useful for debugging purposes. THREE.EdgesGeometry shows just the edges of another geometry, and THREE.WireframeGeometry can be used to show the wireframe of some other geometry.

Finally, if you want to create 3D text, Three.js provides TextGeometry, where you can pass in a font that you want to use. Three.js comes with a couple of fonts, but you can also create your own fonts. However, remember that complex fonts often won’t convert correctly. An alternative to using TextGeometry is using the Troika library, which makes it very easy to create 2D text labels and place them anywhere in the scene.

Until now, we looked at solid (or wireframe) geometries, where vertices are connected to each other to form faces. In the upcoming chapter, we’ll look at an alternative way of visualizing geometries using something called particles or points. With particles, we don’t render complete geometries — we just render the individual vertices as points in space. This allows you to create great-looking 3D effects that perform well.