Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguishable color generation in javascript

I would like to know if there is a simple algorithm (or jQuery plugin) to select distinguishable colors, up to about 20 different colors. If there is not, where can I find an array of distinguishable colors that I could use directly ?

My use case is to generate different colors for pie charts.

like image 746
Benjamin Crouzier Avatar asked Jan 24 '12 13:01

Benjamin Crouzier


People also ask

How do I generate a random color in CSS?

There is no way to do this using CSS only. CSS doesn't support logical statements because CSS is purely deterministic (there is nothing like array etc in CSS). We can use client-side JavaScript to select a random color from the array.

How do you get random colors in react?

Import: Use Javascript import method import randomColor package inside your React Component File.


1 Answers

My idea is to start from HSV color model and walk around the perimeter (hue) with maximal saturation and value:

function hsvToRgb(h, s, v) {
  //... see e.g.: http://snipplr.com/view/14590
}

function distinctColors(count) {
    var colors = [];
    for(hue = 0; hue < 360; hue += 360 / count) {
        colors.push(hsvToRgb(hue, 100, 100));
    }
    return colors;
}

The distinctColors(10) produces:

[[255, 0, 0], [255, 153, 0], [204, 255, 0], [51, 255, 0], [0, 255, 102], [0, 255, 255], [0, 102, 255], [51, 0, 255], [204, 0, 255], [255, 0, 153]]

Hard to tell by only looking at RGB values, but they should be as different as possible. I have taken the hsvToRgb() implementation from here.

like image 198
Tomasz Nurkiewicz Avatar answered Sep 27 '22 23:09

Tomasz Nurkiewicz