Search code examples
javascriptfontsp5.js

Loading a font from a file to use in a P5.JS dom element


I'm currently having trouble using custom fonts within p5.js dom. I can load the font into a var but have no idea how to style a specific element with that var.

This is what I've tried...

var robotoReg = loadFont("Roboto-Regular.ttf");
document.getElementById("mStockOne").style.fontFamily = "robotoReg";

Any help would be appreciated.


Solution

  • You just have to store the font in a global variable :

    var myFont, fontReady = false;
    
    function fontRead(){
        fontReady = true; }
    
    function preload() {
        myFont = loadFont("./fonts/MyfontFile.ttf", fontRead); } //replace with correct path
    
    function setup() {
        createCanvas(720, 400);
        doyourSetup(); }
    
    function draw() {
        background(255);
        if (fontReady) {
            textFont(myFont);
            text("Hello World!", 10, 30);
        }
     }
    

    Sorry for the incorrect formatting im on mobile