Typography

Text

Similar to how we were drawing shapes in the previous section, we can also draw text. The positioning and sizing of text works with the same pixel numbers, as for drawing shapes like circles or squares. Besides the origin of our text (x/y), we can also define at what point our text breaks into a new line:

VIDEO COMING SOON

text(text:string, x:number, y:number, width*:number);
function draw() {
text("Hello World", 50, 50, 500);
}

Like in every other graphic editing software, we have various options to modify the layout and appearance of our text. With textAlign we can define (LEFT/RIGHT/CENTER) in which direct our text flows from the origin (x/y):

textAlign(alignment:LEFT|RIGHT|CENTER);
function draw() {
textAlign(LEFT);
}

The font size textSize, the line height textLeading and font style textStyle can also be defined. Similar to color definitions, everything is read and applied from top to bottom of the code, once a setting is defined, it is being used until overwritten by another setting.

textSize(font size:number);
textLeading(line height:number);
textStyle(font style:NORMAL|ITALIC|BOLD|BOLDITALIC);
function draw() {
textSize(20);
textLeading(24);
textStyle(ITALIC);
text("Hello World", 50, 50);
}

Line breaks

Line breaks cannot simply be added in the text function. Instead, we need to use a special character (\n) to indicate a line break:

function draw() {
text("Hello\nWorld", 50, 50);
}

Loading fonts

Over the years, a couple of system fonts have become ubiquitous on all systems (Arial, Verdana, Tahoma, Trebuchet MS, Times New Roman, Georgia, Courier New, Brush Script M7, Impact). These can be used very easily:

textFont(font family:string|font-variable);
function draw() {
textFont("Times New Roman");
text("Hello World", 50, 50);
}

Other fonts need to be loaded first, to be used in our code. This needs to happen in the preload function:

loadFont(path/file name:string);
let myFont;
function preload() {
myFont = loadFont('FHP-Bold.ttf');
}

function draw() {
textFont(myFont);
text("Hello World", 50, 50);
}

The path to the font file needs to be set correctly. If you are unsure about this part, simply copy your font file into the same folder as your index.html file, then you only need to use the correct file name. Sometimes there are problems with spaces in file names or other special characters.

Text width

If you need to know the width of your text, for example to put a colored rectangle underneath your text, there is a simple function to get the width of your text, which is dependent on the font family, font size, etc.:

textWidth(text:string);
function draw() {
let widthOfText = textWidth("Hello World");
rect(0, 0, widthOfText, 10);
}

Back to top