Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate 2 colors where one of them is a shade of the other one?

Tags:

javascript

css

Basically, I'm generating a random graph with D3.js and I would like to generate a random fill-color and border-color for each node, the border color has to be a shade of the fill color. I'm currently using something like this to generate random fill-color:

randomColor() {
  const r = () => Math.floor(256 * Math.random());
  return  {color: `rgb(${r()}, ${r()}, ${r()})`, border: `rgb(${r()}, ${r()}, ${r()})`};
}

But the border is also random so it's not linked with the main color.

Thanks in advance.

like image 749
ryuzak1 Avatar asked Oct 15 '22 01:10

ryuzak1


1 Answers

You just have to keep the chosen RGB values randomly generated and divide them by a ratio, 2 here:

function randomColor() {
  const rnd = () => Math.floor(256 * Math.random());
  let r = rnd(), g = rnd(), b = rnd(),
      r2 = parseInt(r / 2), g2 = parseInt(g / 2), b2 = parseInt(b / 2);
  return  {color: `rgb(${r}, ${g}, ${b})`, border: `rgb(${r2}, ${g2}, ${b2})`};
}

let style = randomColor();

document.getElementById('test').style.backgroundColor = style.color;
document.getElementById('test').style.borderColor = style.border;
#test {
  border: 5px solid white;
}
<div id="test">TEST</div>
like image 200
Kaddath Avatar answered Nov 15 '22 08:11

Kaddath