I am working on 2D arrays to create a bookshelf, and wanted to have random colors assigned to each book. I have the code working, with 14 hex colors randomly chosen at each refresh, and applied to each of the 14 books. But I wanted to improve my code, so this error does not show up:
p5.min.js:7 Uncaught Error: [object Arguments]is not a valid color representation.
at d.Color._parseInputs (p5.min.js:7)
at new d.Color (p5.min.js:6)
at e.d.color (p5.min.js:6)
at d.Renderer2D.fill (p5.min.js:8)
at e.d.fill (p5.min.js:7)
at draw (sketch.js:38)
at e.redraw (p5.min.js:8)
at e.<anonymous> (p5.min.js:7)
const colors = [];
var randomColor;
var colorCounter;
var bookCounter;
function setup() {
createCanvas(800, 600);
background(200);
colorCounter = 0;
bookCounter = 1;
for (var i = 0; i < 14; i++) {
const randomColor = Math.floor(Math.random() * 16777215).toString(16);
colors.push("#" + randomColor);
};
console.log(colors);
}
function draw() {
stroke(0, 0, 200);
strokeWeight(5);
noFill()
rect(45, 45, 360, 200);
rect(45, 250, 360, 205);
for (var k = 0; k < 14; k++) {
noStroke();
fill(colors[k]);
rect(50 + k * 20, 550, 20, 20);
}
for (var i = 0; i < 2; i++) {
for (var j = 0; j < 7; j++) {
stroke(150, 0, 0);
console.log("Before: " + colorCounter);
fill(colors[colorCounter]);
colorCounter += 1;
console.log("After: " + colorCounter);
rect(50 + j * 50, 50 + i * 200, 50, 200);
}
}
for (var i = 0; i < 2; i++) {
for (var j = 0; j < 7; j++) {
noStroke();
textSize(20);
fill(255);
text("B\no\no\nk\n \n" + bookCounter, 70 + j * 50, 80 + i * 200, 100);
bookCounter += 1;
}
}
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>
This error occurs when you pass something that is not a valid color specification (a number, string, or Color object) to the fill()
function. This includes passing undefined
.
The error being raised in this case the result of colorCounter
being a global variable, which is only set to 0 in setup()
, and the fact that by default the draw()
function is called repeatedly. You can see from your console log output that the error occurs right after "Before: 14" is displayed. The value of colorCounter
is therefore 14
and you the try to call fill(colors[colorCounter])
. Since colors
has a length of 14, the index of the last element is 13, so colors[colorCounter]
returns undefined.
You can fix this error in one of two ways: 1) reset the values colorCounter and bookCounter in the draw()
function, or 2) call noLoop()
in your setup function so that the sketch is only drawn once.