Why is textBounds() returning undefined in p5 npm package but working in web editor?

I’m having trouble with the textBounds() function in the p5 npm package. It keeps returning undefined no matter what I do. Here’s a simplified version of my code:

import p5 from 'p5';

const sketch = (p) => {
  let myFont;

  p.preload = () => {
    myFont = p.loadFont('path/to/font.otf');
  };

  p.setup = () => {
    p.createCanvas(400, 400);
    let textArea = myFont.textBounds('Hello', 0, 0, 20);
    console.log(textArea); // This is undefined
  };
};

new p5(sketch);

I’ve confirmed that the font loads correctly and the textBounds function exists on the font object. But when I try to use it, I get undefined. Oddly enough, the same code works fine in the p5 web editor.

I’ve tried reinstalling the package twice, but no luck. Am I missing something obvious? Is there a difference in how the npm package handles textBounds compared to the web editor?

hey there! i had a similar issue. have u tried using p.textBounds() instead of myFont.textBounds()? sometimes the p5 npm package is a bit quirky with font methods. also, make sure ur font path is correct. if that doesn’t work, maybe try using a different p5 version? hope this helps!

I’ve actually run into this exact problem before. The issue is likely related to how the npm package handles font loading compared to the web editor. One thing that worked for me was wrapping the textBounds() call in a setTimeout function to give the font a bit more time to fully load. Something like this:

p.setup = () => {
  p.createCanvas(400, 400);
  setTimeout(() => {
    let textArea = myFont.textBounds('Hello', 0, 0, 20);
    console.log(textArea);
  }, 100);
};

This isn’t the most elegant solution, but it got things working for me. If that doesn’t do the trick, you might want to look into using a font loading library like WebFont Loader to ensure your font is fully loaded before you try to use it. Hope this helps!

I’ve encountered this issue before when working with the p5 npm package. One thing to check is the timing of your textBounds() call. Try moving it to the draw() function instead of setup(). The font might not be fully loaded when setup() runs, even if preload() completes.

Also, ensure you’re using the latest version of p5. There have been bug fixes related to text functions in recent updates. If the problem persists, you might want to consider using a workaround like manually calculating text dimensions using textWidth() and textAscent()/textDescent().

Lastly, double-check that your font file is being bundled correctly with your project when using npm. Sometimes build processes can affect asset loading.