关于Processing全局与局部变量示例的两类技术问询
Hey there! Let’s walk through your two questions about these Processing examples clearly, step by step.
1. Is your guess about Example 1 correct?
Absolutely right! Here’s why:
In Processing, the draw() function runs on a loop by default (around 60 times per second). In Example 1, you declare int count = 0 inside draw()—this makes count a local variable, which means its scope is limited to a single run of draw().
Every time draw() loops back around, it creates a brand new count variable, sets it to 0, adds 1 to get 1, then uses that value for background(). The result? The background stays stuck at a very dark gray (since background(1) is nearly black) instead of fading to white like you might expect.
To confirm, here’s the key snippet from Example 1:
void draw() { int count = 0; // Reset to 0 EVERY time draw() runs count = count + 1; background(count); }
2. Why does Example 2 switch to a black-to-blue cycle, and how to fix it?
Let’s break down the behavior first, then cover practical fixes:
What’s happening
In Example 2, count is a global variable, so it persists across every draw() loop. At first, count increments from 0 to 255: since background() with a single integer uses grayscale (0 = black, 255 = white), you see a smooth fade from black to white.
But once count goes past 255, Processing stops treating that integer as a grayscale value. Instead, it interprets the number as a full 32-bit color code. For example:
count = 256translates to the color code0x00000100, which is a very dark blue (only the blue channel has a tiny value)- As
countincrements to 511, the blue channel goes from 1 to 255, creating a fade from near-black to pure blue
How to avoid this
If you want to stick to the grayscale cycle (black → white → black → white) or stop at white, here are two straightforward fixes:
Fix 1: Use modulo arithmetic to loop between 0-255
This resets count to 0 as soon as it hits 256, keeping the fade strictly in grayscale:
int count = 0; void setup() { size(200,200); } void draw() { count = (count + 1) % 256; // Loop back to 0 after 255 background(count); }
Fix 2: Constrain the value to stay within 0-255
If you want the fade to stop at white instead of looping, use constrain() to cap the value:
int count = 0; void setup() { size(200,200); } void draw() { count = constrain(count + 1, 0, 255); // Stop incrementing at 255 background(count); }
You can also use an if statement for more manual control over when the loop restarts:
int count = 0; void setup() { size(200,200); } void draw() { count = count + 1; if (count > 255) { count = 0; // Reset to black once we hit white } background(count); }
内容的提问来源于stack exchange,提问作者Nicholas Hoyt

