Hi, Very new to programming, and its concepts so I’m trying to create a random color generator that I can call anytime to provide my r,g,b values.
This is what I wrote:
let x;
let y;
let col = {
r: [],
g: [],
b: [],
};
function setup() {
createCanvas(600, 600);
background(255);
}
function draw() {
randomCol();
fill(col.r, col.g, col.b);
ellipse(mouseX, mouseY, 15, 15);
randomCol();
fill(col.r, col.g, col.b);
ellipse(mouseX + 50, mouseY + 50, 15, 15);
}
function randomCol() {
while (col.r < 1 && col.g < 1 && col.b < 1) {
col.r = random(0, 255);
col.g = random(0, 255);
col.b = random(0, 255);
}
}
My problem is that when I call the function I get the same color for every element. I tried using push and pop but that didn’t help. Can anyone shed light on why this doesn’t work?
you can create an array or just separate variables if there is only a few.
As separate variables
let x;
let y;
let colorA;
let colorB;
function setup() {
createCanvas(600, 600);
background(255);
colorA = getRandomColor();
colorB = getRandomColor();
}
function draw() {
fill(colorA.r, colorA.g, colorA.b);
ellipse(mouseX, mouseY, 15, 15);
fill(colorB.r, colorB.g, colorB.b);
ellipse(mouseX + 50, mouseY + 50, 15, 15);
}
function getRandomColor() {
//you probably need to floor these values
return { r: random(255), g: random(255), b: random(255) };
}
or as an array of colors
let x;
let y;
let colors;
function setup() {
createCanvas(600, 600);
background(255);
noStroke();
var amtOfColors = 10;
colors = [];
for(var i = 0; i < amtOfColors; i++) {
colors.push(getRandomColor());
}
}
function draw() {
var rectSize = width / colors.length;
for(var i = 0; i < colors.length; i++) {
let x = i * rectSize
let y = height / 2 - rectSize / 2;
let col = colors[i];
fill(col.r, col.g, col.b);
rect(x, y, rectSize, rectSize);
}
}
function getRandomColor() {
//you probably need to floor these values
return { r: random(255), g: random(255), b: random(255) };
}