How to isolate primary colors from a background color extraction from css


I want to make a non-canvas html element change color in a pattern based off it’s current color using javascript

in the example, boxyBox has a background color of rgba(100, 100, 100, 0.9), and I want to change the background color of any element with an alpha value of less than 1

var box = document.getElementById("boxyBox");
var styleOfBox = window.getComputedStyle(box);
var colorOfBox = styleOfBox.getPropertyValue("background-color");
console.log(colorOfBox); //returns rgba(100, 100, 100, 0.9);
console.log(typeof colorOfBox); //returns string
var alphaOfBox = ???;
if(alphaOfBox < 1) { = red;

Is there a way to extract individual primary color values, or to parse them from the background color string?


After a few hours more of fumbling about, I found this solution

var box = document.getElementById("boxyBox");
var styleOfBox = window.getComputedStyle(box);
var colorArr = styleOfBox.getPropertyValue("background-color").split(", ");
var red = parseFloat(colorArr[0].match(/[\d\.]+/)[0]);
var green = parseFloat(colorArr[1]);
var blue;
var alpha;
if(typeof colorArr[3] == "string") {
    alpha = parseFloat(colorArr[3].match(/[\d\.]+/)[0]);
    blue = parseFloat(colorArr[2]);
else {
    blue = parseFloat(colorArr[2].match(/[\d\.]+/)[0]);
    alpha = 1;

these variables now correspond to the primary computer color they are named after, including non-rgba and decimal values in the stylesheet

Answered By – Esdeseserdt1976

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published