Loading a JSON font
To start, it is necessary to load a font in the JSON format with Three.JS.
For this, we must use the class FontLoader
.
const loader = new THREE.FontLoader(); loader.load( 'https://threejs.org/examples/fonts/helvetiker_regular.typeface.json', function ( font ) { [...] });
The method load
that we use requires two parameters :
- The path to the JSON character font file
- A callback function – executed at the end of loading
The next steps resulting in the creation of the 3D text object will occur in the body of the callback function.
Creating the 3D text object
Mesh Material
The next step consists of creating the Three.JS Material
of the 3D object; here we choose a MeshBasicMaterial
.
As a reminder, a Material
represents the visual aspect, the texture, and the diverse rendering options (brilliance, opacity, texture…) of a 3D object.
const matLite = new THREE.MeshBasicMaterial( { color: 0x2c3e50, transparent: true, opacity: 0.8, side: THREE.DoubleSide } );
We specify the opacity and color of the text to be created. The property DoubleSide
is important for rendering a flat 3D object visible from its two faces.
Mesh Geometry
It is now time to create the Geometry
of our text, the form of its 3D structure.
For this, we use the variable font
, a variable passed as a parameter of the function callback. This variable represents the JavaScript object returned by load
, the result of the JSON file loading.
The variable shapes
is an instance of Font
class . This class makes available the function generateShapes
.
const message = " Three.js\nUniversity"; const shapes = font.generateShapes( message, 100 ); const geometry = new THREE.ShapeGeometry( shapes ); geometry.computeBoundingBox();
Thus, we create the Geometry
of our text, the 3D form of its structure.
Optionally, we take this chance to center the Geometry on itself.
const xMid = - 0.5 * ( geometry.boundingBox.max.x - geometry.boundingBox.min.x ); geometry.translate( xMid, 0, 0 );
Finalizing the 3D text object
By combining the Geometry
and the Material
in the preceding paragraphs, we can create a 3D object usable in the scene, an instance of Mesh
.
text = new THREE.Mesh( geometry, matLite ); text.position.z = - 150; scene.add( text );
Final result
See the Pen Three.JS Simple Text – Json font by Thomas (@thomassifferlen) on CodePen.
[…] 22 juin 202125 août 2021 thomassifferlen 1 commentaire Available in English […]
Example doesn’t work
Oh yes, unfortunately it seems deprecated, I’m going to fix it soon !
Thanks for your return