Many developers design Color codes and scale with the CSS, pick the color from some online color palette. However, it is not everyone’s favorite tool. The good news is we have the Chroma.js, a small library that can be a big help with generating the color scale within the JavaScript code. This means you can plug it into your JavaScript framework directly!

Let’s get started!

Install

In your web application, you can use a link from CDNJS in your HTML doc

<script src="https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js" integrity="sha512-yocoLferfPbcwpCMr8v/B0AB4SWpJlouBwgE0D3ZHaiP1nuu5djZclFEIj9znuqghaZ3tdCMRrreLoM8km+jIQ==" crossorigin="anonymous"></script>

Or, you can install it using the NPM as well.

$ npm install chroma-js

Example Usage

You can simply create a color scale within your JavaScript code with chroma.scale([<color1>,<color2>, ... , <color n>]) function which will create the color scale between the colors you assign.

For example, you can create a color scale from yellow to red with the following script:

var color_scale = chroma.scale([‘yellow’, ‘red’]);

Then, you can access the color in RGB or in HEX code by

color_scale(0).rgb()    // [255, 255, 0]
color_scale(0.1).rgb()  // [255, 230, 0]
color_scale(0.2).rgb()  // [255, 204, 0]
color_scale(0.3).rgb()  // [255, 179, 0]
...
color_scale(1.0).rgb()  // [255, 0, 0]
===================================
color_scale(0).hex()    // "#ffff00"
color_scale(0.1).hex()  // "#ffe600"
color_scale(0.2).hex()  // "#ffcc00"
color_scale(0.3).hex()  // "#ffb300"
...
color_scale(1.0).hex()  // "#ff0000"

#programming #colors #data-visualization #scaling #data-science

Color Scales in JavaScript with Chroma.js
9.25 GEEK