Creating A 3D Text object

Text

The created mesh will be 3D object created as an extrusion of a given text. It will have its origin at the center of the text.

Prerequesite

The MeshBuilder.CreateText is leveraging our ExtrudePolygon feature which requires you to have Earcut library available. Whilst an Earcut script is pre-loaded in the Playground you will have to add a reference to such a script in your own projects. One is available at cdn or via a npm package.

MeshBuilder

Usage :

const fontData = await (await fetch("./fonts/Droid Sans_Regular.json")).json(); // Providing you have a font data file at that location
const text = BABYLON.MeshBuilder.CreateText(
"myText",
"Hello World !! @ #$ % é",
fontData,
{
size: 16,
resolution: 64,
depth: 10,
},
scene,
);
options propertyvaluedefault value
options property
size
value
(number) size of each letter
default value
50
options property
resolution
value
(number) number of points used when tracing curves
default value
8
options property
depth
value
(number) extrusion depth (on Y axis)
default value
1.0
options property
sideOrientation
value
(number) side orientation
default value
DOUBLESIDE

Generating font data

To be able to trace and extrude the mesh, you have to provide font data information. Babylon.js is supporting the fantastic work done by Gero3 on http://gero3.github.io/facetype.js/

Simply go to this site and generate the json description file for the font you want to use.

We are also offering already exported fonts on assets.babylonjs.com:

Examples

Hello world: Create a 3d text

Controlling letters texture mapping and colors

You can use a specific parameter to set the way the UVs and colors are attached on the new mesh:

var myText = BABYLON.MeshBuilder.CreateText("myText", "HELLO WORLD", fontData, {
size: 16,
resolution: 64,
depth: 10,
faceUV: [
new BABYLON.Vector4(0, 0, 1, 1),
new BABYLON.Vector4(0, 0, 1, 1),
new BABYLON.Vector4(0, 0, 1, 1),
];
});

The faceUV array defines an array of Vector4 elements used to set different texture coordinates to the front, top and back faces respectively. You can do the same for colors with faceColors.

But you may want to go further and control the texture coordinates or colors per letter. To do so you can use the following code:

const letterCount = 10;
const step = 1 / letterCount;
var myText = BABYLON.MeshBuilder.CreateText("myText", "HELLO WORLD", fontData, {
size: 16,
resolution: 64,
depth: 10,
perLetterFaceUV: (index) => {
const startX = index * step;
return [
new BABYLON.Vector4(startX, 0, startX + step, 1),
new BABYLON.Vector4(startX, 0, startX + step, 1),
new BABYLON.Vector4(startX, 0, startX + step, 1),
];
}
});

The perLetterFaceUV (and its sister perLetterFaceColors) is a callback used to provide the data per letter instead of per mesh.

Create a 3d text