user3206440
user3206440

Reputation: 5049

Colors from RGB values in JavaScript array

What is the preferred way to create colors with JavaScript from RGB colors so that they can then be used to style elements as in the form of CSS colors like the following.

document.getElementById("some_id").style.color = "some_value"

Example below:

const colorsCbfRainbowRGB = {
  violet: [120,28,129],
  indigo: [64,67,153],
  blue: [72,139,194],
  green: [107,178,140],
  olive: [159,190,87],
  yellow: [210,179,63],
  orange: [231,126,49],
  red: [217,33,32]
}

Upvotes: 5

Views: 12588

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386520

You could use a string template with rgb() and RGB numbers.

function setColor(color) {
    const colorsCbfRainbowRGB = { violet: [120, 28, 129], indigo: [64, 67, 153], blue: [72, 139, 194], green: [107, 178, 140], olive: [159, 190, 87], yellow: [210, 179, 63], orange: [231, 126, 49], red: [217, 33, 32] };
    document.getElementById("out").style.color = `rgb(${colorsCbfRainbowRGB[color]})`;
}

setColor('orange');
<div id="out">foo bar baz</div>

Upvotes: 2

Naghaveer R
Naghaveer R

Reputation: 2944

Create random color(it's not only RGB colors)

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
      for (var i = 0; i < 6; i++ ) {
          color += letters[Math.floor(Math.random() * 16)];
      }
    return color;
}

Hope this Helps!!!

Upvotes: 1

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60507

You can convert to rgb(r, g, b) CSS colors very easily.

function rgb(values) {
    return 'rgb(' + values.join(', ') + ')';
}
console.log(rgb(colorsCbfRainbowRGB.violet));

This is supported by any browser worth mentioning, and simpiler than converting to hexadecimal.

Upvotes: 5

Edoardo Morassutto
Edoardo Morassutto

Reputation: 360

Use the hex rappresentation of a color: #rrggbb

Where rr is the amount of red from 00 to FF, gg the green and bb the blue.

Upvotes: 0

Related Questions