21

What would be the easiest way to transform

$('#my_element').css('backgroundColor')

to object like this:

{ r: red_value, g: green_value, b: blue_value, a: alpha_value }

?

0

8 Answers 8

29
var c = $('body').css('background-color');
var rgb = c.replace(/^(rgb|rgba)\(/,'').replace(/\)$/,'').replace(/\s/g,'').split(',');

for(var i in rgb) {
  console.log(rgb[i]);
}

Try it here http://jsbin.com/uhawa4

Edit :

var c = $('body').css('background-color');
var rgb = c.replace(/^rgba?\(|\s+|\)$/g,'').split(',');

for(var i in rgb) {
  console.log(rgb[i]);
}

or even simpler way, just aiming at numbers

var c = 'rgba(60,4,2,6)';
var rgb = c.match(/\d+/g);

for(var i in rgb) {
  console.log(rgb[i]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ! This is pretty close to what I was looking for :)
Replace var rgb = c.match(/\d+/g); with var rgb = c.match(/[.?\d]+/g); in order to match floating point numbers for alpha in rgba strings correctly such as rgba(60,4,2,0.3)
3

As seen here:

R = hexToR("#FFFFFF");
G = hexToG("#FFFFFF");
B = hexToB("#FFFFFF");

function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

This script basically takes each color pair from your hexcolor code (for example #F0556A) and switches it to a integer using parseInt with base 16 .

1 Comment

It's good form to archive the important parts of links in your answer, so that it doesn't lose most of its value if the link dies.
2

You would do something like:

$.fn.ToRgb = function()
{
    if(this.charAt(0) == "#"){this = this.substring(1,7);} //remove the #
    return {
        R : parseInt(this.substring(0,2) ,16),
        G : parseInt(this.substring(2,4) ,16),
        B : parseInt(this.substring(4,6) ,16),
    }
}

RGB = $('#my_element').css('backgroundColor').ToRgb();


/*
   * console.log(rgb) =>
   * {
   *   R: X
   *   G: X
   *   B: X 
   * }
*/

Pretty simple :)

5 Comments

I see that $('#my_element').css('backgroundColor') always returns something like rgb(123, 87, 92) or rgba(123, 87, 92, 0.7). Can it return also things like #123456 or 123456 ?
This was not specifically asked for
@Robert - it was implied that the input would be something like rgba(...) since a simple hex value like #6400FF cannot express opacity.
Which browser does this work in out of interest? I always forget which ones return things of the form "rgb(a,b,c)" and what might return other forms...
this should be cross-browser friendly.
2

To convert rgba string to object with keys:

convertRGBtoOBJ(colorString)
{
  const rgbKeys = ['r', 'g', 'b', 'a'];
  let rgbObj = {};
  let color = colorString.replace(/^rgba?\(|\s+|\)$/g,'').split(',');

  for (let i in rgbKeys)
    rgbObj[rgbKeys[i]] = color[i] || 1;

  return rgbObj;
}

console.log(convertRGBtoOBJ('rgba(23,54,230,0.5)'))

/*
  Object {r: "23", g: "54", b: "230", a: 0.5}
*/

Comments

1

Say you have the following CSS rule:

#my_element {
    background-color: rgba(100, 0, 255, 0.5);
}

Then this is how you could get an RBGA object:

var colorStr = $('#my_element').css('backgroundColor'); // "rgba(100, 0, 255, 0.5)"

// using string methods
colorStr = colorStr.slice(colorStr.indexOf('(') + 1, colorStr.indexOf(')')); // "100, 0, 255, 0.5"
var colorArr = colorStr.split(','),
    i = colorArr.length;

while (i--)
{
    colorArr[i] = parseInt(colorArr[i], 10);
}

var colorObj = {
    r: colorArr[0],
    g: colorArr[1],
    b: colorArr[2],
    a: colorArr[3]
}

Comments

1

Simple function to extract the RGB numeric values

function extractRgb (css) {
  return css.match(/[0-9.]+/gi)
}
console.log(extractRgb('rgb(255, 255, 255)'))
console.log(extractRgb('rgba(255, 255, 255, 0.7)'))

Comments

1

A JS-native CanvasRenderingContext2D instance can read any CSS-formatted color (as a string) and write it in a RGBA buffer (0 to 255) for you :

const color2rgba = (string) => {
  const canvas = document.createElement("canvas");
  canvas.width = canvas.height = 1;
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = string;
  ctx.fillRect(0, 0, 1, 1);
  const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
  return {r, g, b, a};
};

const rgba = color2rgba("deeppink");
console.log(rgba);  // {r: 254, g: 20, b: 146, a: 255}

This function may have poor performance but can be greatly optimized by always recycling (using clearRect) the same "ctx" object.

3 Comments

Why the {willReadFrequently: true} if you call cssColor_to_rgba255Color on-demand (on a brand new HTMLCanvasElement)?
Also the requirement is to return an Object, so const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data; return {r, g, b, a}; would give the expected result.
The "willReadFrequently" is useful if you optimise this function by always recycling (using clearRect) the same "ctx" object. Besides that, thank you for the return statement correction.
0

More simple:

 //javascript code
 var color = $('#my_element').css('backgroundColor');
 var rgb = /rgb\((\d+), (\d+), (\d+)\)/.exec(color);
  var r = rgb[1],
      g = rgb[2],
      b = rgb[3];
  console.log('Red  :' + r);
  console.log('Green:' + g);
  console.log('Blue :' + b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.