Easy 'for loop' question

What am I missing here? I’m expecting that the background should cycle through from black to white. …it’s not.

function setup() {
	createCanvas(100, 100);
}

function draw() {
	for (let x = 0; x < 256; x++) {
		background(x);
		print(x);
	}
}

Thanks!

1 Like

There is nothing wrong with the code,
though you perform a for loop over 255 colors, the last one is 255.
then it exits the loop and the color remaining is 255 ( = white).
the framerate is slow so only the last one will be shown.

(let x = 0; x < 130; x++) { <-- would give a grey background

2 Likes

RIGHT! I forgot that the for loop all happens within one frame!

Thanks :slight_smile:

1 Like

you can replace the for-loop by the looping of draw() itself

then each step is visible as a frame on its own



let x = 0;

function setup() {
	createCanvas(100, 100);
	frameRate(22);
}

function draw() {
	background(x);
	x++;
	// print(x);
}
1 Like