Processing and p5.js color work very differently, and that is surprising. There is a lot of great information on how / why above, but here is a walkthrough of a solution to your students using get()
as a color detector in their projects.
In Processing (Java mode),
get()
and color()
return the same things (the color datatype, a 32-bit int representing ARGB), which can be compared using ==
.
Letās detect if the mouse is on white:
// check mouse color
void setup() {
size(100,100);
rect(25,25,50,50);
}
void draw() {
int cwhite = color(255);
int cmouse = get(mouseX, mouseY);
if(cmouse==cwhite) {
println(frameCount, cmouse);
}
}
In p5.js (JavaScript),
get()
and color()
return DIFFERENT things, AND, those things canāt be compared with equals ā to each other, OR to themselves(!!). get()
returns an array of floats [R, G, B, A]. color()
returns a p5.Color object, which contains multiple arrays, including one with four 0-255 values, called ālevelsā. In JavaScript, arrays and objects with the same contents are not found equal with ==
.
To adapt the Processing sketch to p5.js, we need two things:
- define our color to check for as a flat array, [R, G, B, A], so it will match
get()
. Either declare it directly [] or use color(my_arguments).levels
.
- create an equals function to compare two colors. There are many ways to do this, but weāll use one that is easy to read and fast.
// check mouse color
function setup() {
createCanvas(100, 100);
rect(25,25,50,50);
}
function draw() {
let cmouse = get(mouseX, mouseY); // [R, G, B, A]
let cwhite = [255,255,255,255];
// let cwhite = color(255).levels;
if(eqcolor(cmouse, cwhite)) {
print(frameCount, cmouse);
}
}
function eqcolor(a, b) {
return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3];
}
<iframe src="https://editor.p5js.org/jeremydouglass/sketches/JsVeospiC" width="100%" height="510" allowfullscreen frameborder="0" marginwidth="0" marginheight="0"></iframe>