为什么不能在我的 p5 函数中全局引用这些变量?

why can't these variables be referenced globally in my p5 functions?

我无法理解专门定义的 p5 函数如何引用全局定义的变量。像这样的函数——其中一个常量在本地为 p5 函数提供参数——工作得很好。

function setup() {

}

function draw() {
  ellipse(50, 50, 80, 80);
}

但是由于某些原因,我无法使用这样的方法来绘制椭圆:

  var CANVAS_HEIGHT = 1024;
  var CANVAS_WIDTH = 768;
  var RADIUS = 150;
  var circleColor = 150;
  var bgColor = 50;

  function setup() {
    backgroundColor = color(bgColor);
    createCanvas(CANVAS_WIDTH, CANVAS_HEIGHT);          
  }


  function draw() {
    fill(circleColor);
    ellipse(CANVAS_WIDTH/2, CANVAS_HEIGHT/2, RADIUS*2, RADIUS*2);

  }

显然设置函数确实创建了一个 canvas 引用全局变量。但是,绘制函数似乎没有引用它们。我在这里错过了什么?感谢您的帮助。

您不能在 setup() 函数中使用这样的变量。

你必须直接使用这些值,并且你必须在setup()函数中分配变量:

  var CANVAS_HEIGHT;
  var CANVAS_WIDTH;
  var RADIUS;
  var circleColor;
  var bgColor;

  function setup() {
    backgroundColor = color(50);
    createCanvas(1024, 768);  

    CANVAS_HEIGHT = 1024;
    CANVAS_WIDTH = 768;
    RADIUS = 150;
    circleColor = 150;
    bgColor = 50;        
  } 

来自p5.js faq

Why can't I assign variables using p5 functions and variables before setup()?

In global mode, p5 variable and function names are not available outside setup(), draw(), mousePressed(), etc. (Except in the case where they are placed inside functions that are called by one of these methods.) What this means is that when declaring variables before setup(), you will need to assign them values inside setup() if you wish to use p5 functions. For example:

var n;
function setup() {
  createCanvas(100, 100);
  n = random(100);
}

The explanation for this is a little complicated, but it has to do with the way the library is setup in order to support both global and instance mode. To understand what's happening, let's first look at the order things happen when a page with p5 is loaded (in global mode).

Scripts in are loaded. of HTML page loads (when this is complete, the onload event fires, which then triggers step 3). p5 is started, all functions are added to the global namespace. So the issue is that the scripts are loaded and evaluated before p5 is started, when it's not yet aware of the p5 variables. If we try to call them here, they will cause an error. However, when we use p5 function calls inside setup() and draw() this is ok, because the browser doesn't look inside functions when the scripts are first loaded. This is because the setup() and draw() functions are not called in the user code, they are only defined, so the stuff inside of them isn't run or evaluated yet.

It's not until p5 is started up that the setup() function is actually run (p5 calls it for you), and at this point, the p5 functions exist in the global namespace.