I am creating DOM buttons in P5.js, that I want to apply styling to. In this case I want to change the background color. Normally this would be applied by doing this.
button.style("background-color", "black");
In my case I want to reference a color already stored in a JS array, as the colors are being uniformly used, like this.
swatch.style("background-color", colArray[0]);
Obviously this does not work, as the style is being applied from CSS. Any suggestions would be aces.
I could store the colors in CSS and reference a style, but I am trying to avoid double handling.
No error messages in the console for JS. Just a plain CSS issue.
You can't use the color value directly because it's an object that CSS doesn't understand, but you can format it into a string that CSS does understand. In p5.js you can use the red(), green(), and blue() functions to get the RGB values from the color.
Then once you have those values, I can think of two approaches:
Approach one: In CSS, use the rgb() function. It would look something like this:
var rgbString = 'rgb(' + red(myColor) + ', ' + green(myColor) + ', ' + blue(myColor) + ')';
myElement.style('background-color', rgbString);
Approach two: In p5.js, use the hex() function to convert the RGB values into hex.
var rHex = hex(red(myColor));
var gHex = hex(green(myColor));
var bHex = hex(blue(myColor));
var hexColor = '#' + rHex + gHex + bHex;
myElement.style('background-color', hexColor);
I haven't tested this so some of the syntax might be slightly off, but hopefully that gives you the general idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With