String t_str;
void setup() {
fullScreen();
textAlign(CENTER);
textSize(70);
t_str = "add your text";
textSize(12); // To create a "text width factor",
float twf = width/textWidth(t_str);
int f = 4; // Empericaly found
textSize(f*twf); // Making it proportional for other screen resolutions
text(t_str, width/2, height/2);
}
Ideally the most flexible way to do this is to use HTML and CSS to style your text since it’s more powerful and it was made for that.
Now if you want to do this in p5js using only the text() and textStyle(BOLD) functions, you can get inspiration from the Markdown syntax :
I just love **bold text**. → I just love bold text .
So using two asterisks between some portion of text indicate that we want this to be bold.
What if we could have a function to do that automatically for us?
This is my take on this :
function splitByBold(text) {
const result = [];
let previousIndex = 0;
// Indicate wether we are currently in a bold text
let isCurrentBold = false;
// Go through every character
for (let i = 0; i < text.length; i++) {
// True if there's two asterisks from the current index
const isTwoAsterisks = (text[i] == '*') && (i < text.length - 1) && (text[i + 1] == '*');
// True if we are at the end (useful to get the last letter)
const isLastIndex = i == text.length - 1;
// We detected two asterisks
if (isTwoAsterisks || isLastIndex) {
// The last index to take
const lastIndex = isLastIndex ? i + 1 : i;
// Add that piece of text
result.push({
text: text.slice(previousIndex, lastIndex),
bold: isCurrentBold
});
// The previous index becomes the new one, add 2 if two asterisks
previousIndex = isTwoAsterisks ? i + 2 : i;
// Invert the current state
isCurrentBold = !isCurrentBold;
}
}
return result;
}
upside is basically you can do everything you want with html/css but downside is you cannot edit pixels of the text or overlay contents on the text (unless you make another transparent canvas on top of the paragraph)