Creating a 3D Text Mesh
Learn how to create and customize 3D text in Three.js
Introduction to Troika
In this lesson, we’ll take a quick look at how we can create 3D text. First, we’ll look at how to render text using the fonts provided by Three.js and how we can use our own fonts for this. Then, we’ll show a quick example of using an external library called Troika that makes it really easy to create labels and 2D text elements and add them to our scene.
Rendering text
Rendering text in Three.js is very easy. All we have to do is define the font we want to use and apply the same extrude properties we saw when we discussed THREE.ExtrudeGeometry
. The following screenshot shows text in Three.js:
Example: TextGeometry
Let’s execute the text-geometry.js
example in the playground below by clicking the “Run” button:
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') // const CopyWebpackPlugin = require('copy-webpack-plugin') const fs = require('fs').promises // we should search through the directories in examples, and use // the name from the files to generate the HtmlWebpackPlugin settings. module.exports = async () => { return { module: { rules: [ { test: /\.glsl$/i, use: 'raw-loader' } ] }, mode: 'development', entry: { 'chapter-6': './samples/chapters/chapter-6/text-geometry.js', }, output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/', }, plugins: [ new HtmlWebpackPlugin(), ], experiments: { asyncWebAssembly: true }, devServer: { allowedHosts: 'all', host: '0.0.0.0', port: '3000', static: [ { directory: path.join(__dirname, 'assets'), publicPath: '/assets' }, { directory: path.join(__dirname, 'dist') } ] }, mode: 'development', } }
Note: We can change the properties of the text from the right control panel in the output screen.
Creating 3D text
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, we can see that we first have to load the font (line 5). For this, Three.js ...