TextWidth is not the correct width!

If i create a normal line, with “line(startX, startY, startX+textWidth(STRING), startY)” the line is not the correct width. I fixed it by making a “rect()” with the y size on “0.5”!

Hello @Lissie
Welcome the forum. :grin:

Please correct the spelling error in title of your post so that it will be searchable for others with the same question.

I believe “with” should be “width”.

Also, it is not necessary to add clickbait verbiage. The extra wordage takes extra effort to scan the topics.
Kindly remove “if you have the same prob. read this!”
This forum is not a YouTube channel… :upside_down_face: :slightly_smiling_face:

:nerd_face:

3 Likes

Something to do with having to set textSize beforehand…

2 Likes

I have edited the title for this discussion.

2 Likes

textWidth() includes glyph whitespace (aka padding) for every character. Ideally you’d want to ignore this for the first and last characters.

1 Like

In my experience, use createFont and textFont and textSize before textWidth

2 Likes

Yes, at least three criteria need to be established to create a context in order for textWidth() to operate properly. We need a font, a text size, and of course a string. If you don’t set the first two of those criteria explicitly, some default settings will prevail. See the following p5.js code and output:

function setup() {
  createCanvas(400, 400);
  noLoop();
}

function draw() {
  background(220);
  textSize(24);
  textFont('Helvetica');
  print(textWidth('Jabberwocky'));
  textSize(48);
  print(textWidth('Jabberwocky'));
  textFont('Verdana');
  print(textWidth('Jabberwocky'));
  print(textWidth('Fiddlesticks'));
}

Output:

140.0625
280.125
309.7734375
277.8515625
2 Likes