processing / p5.js

p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
http://p5js.org/
GNU Lesser General Public License v2.1
21.4k stars 3.28k forks source link

textWidth gives wrong value on setup function #7128

Closed pvzzombs closed 4 days ago

pvzzombs commented 1 month ago

Most appropriate sub-area of p5.js?

p5.js version

1.9.4

Web browser and version

Brave 1.67.123 Chromium: 126.0.6478.126 (Official Build) (64-bit)

Operating system

Windows 10

Steps to reproduce this

Snippet:


var str = "press space to restart";
var w;

function setup() {
  createCanvas(100, 100);
  w = textWidth(str);
  console.log(w);
}

function draw() {
  str = "press space to restart";
  w = textWidth(str);
  console.log(w);
  noLoop();
}
welcome[bot] commented 1 month ago

Welcome! 👋 Thanks for opening your first issue here! And to ensure the community is able to respond to your issue, please make sure to fill out the inputs in the issue forms. Thank you!

pvzzombs commented 1 month ago

Replication link: JSFiddle. This issue is similar to issue 52.

dhowe commented 1 month ago

I think the problem here is that the variable name shadows the built-in p5 function str() - changing the variable name should fix it (or using let instead of var)

morozgrafix commented 4 days ago

agree with @dhowe Here is a small sketch to illustrate the point regarding using str as variable name, since it's a reserved word for built-in function of p5.js

var s = "press space to restart";
var w;
var w1;

function setup() {
  createCanvas(100, 100);
  w = textWidth(s);
  w1 = textWidth(str);
  console.log(w);
  console.log(w1);
  console.log(str)
}

function draw() {
  s = "press space to restart";
  w = textWidth(s);
  w1 = textWidth(str);
  console.log(w);
  console.log(w1);
  console.log(str);
  noLoop();
}

Console output:

115.3828125
139.41796875
ƒ bound () {}
<constructor>: "Function"
name: "Function"
115.3828125
139.41796875
ƒ bound () {}
<constructor>: "Function"
name: "Function"