0

I'm working with charts.js library and I need to generate random colors for the charts units.

I saw a lot of answers on how to do so. Like Anatoliy answer for example.

The thing is, I need it's equivalent highlight color as well (or any close color) to fulfill the 'highlight' field of the charts.js Pie.

{
    value: 300,
    color: "#30a5ff",
    highlight: "#62b9fb",
    label: "Label"
},
Community
  • 1
  • 1
Jacob
  • 3,598
  • 4
  • 35
  • 56
  • If you vote down, please supply an explanation at least. I think this is very common scenario when working with charts.js. – Jacob Feb 10 '17 at 02:07
  • 1
    What is the relationship between the original color and the highlight color? Color complement? Just two randomly different colors? Same hue but darker/brighter? ... – Andrew Willems Feb 10 '17 at 02:17
  • As I wrote, any close color would be fine, The brighter would be perfect. – Jacob Feb 10 '17 at 02:27
  • You've given me something to work with, I suppose, but what do you mean by "close"? Same hue but slightly different brightness? Same brightness but slightly different hue? Just vaguely somewhere close on the colour wheel? Something else? – Andrew Willems Feb 10 '17 at 02:32
  • 1
    work with HSL color values, i.e. `hsl(hue, saturation, light)` makes this sort of thing trivial - supported even in IE since IE9 – Jaromanda X Feb 10 '17 at 02:40
  • @AndrewWillems A little bit brightness from the original color will be good. – Jacob Feb 10 '17 at 02:43
  • @JaromandaX This is perfect. I didn't know about this possibility. Thank you !. – Jacob Feb 10 '17 at 02:45

1 Answers1

2

Here's one among many possible solutions. Get a random hue between 0 and 360. Use 100% saturation and 50% lightness for the main color, and 100% saturation and, say, 80% lightness for the "highlight" color. Just keep clicking the "Run code snippet" button to see more random colors.

document.querySelectorAll('div').forEach(d => {
  const hue = Math.floor(Math.random() * 360);
  d.style.backgroundColor = `hsl(${hue}, 100%, 50%)`;
  d.style.borderColor     = `hsl(${hue}, 100%, 80%)`;
});
div {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: solid 5px;
  margin: 5px;
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Andrew Willems
  • 11,880
  • 10
  • 53
  • 70