1.0.0 • Published 2 years ago

number-to-color v1.0.0

Weekly downloads
78
License
MIT
Repository
github
Last release
2 years ago

JavaScript Number to Color converter

npm npm GitHub issues

This small and fast library maps a range of numbers to a circular palette of colors. It varies hue (with saturation and lightness equal to 1) and returns RGB in different formats.

import { numberToColor } from 'number-to-color'
// numberToColor(number from 0 to max − 1, max)
const tenthColorOfSixteen = numberToColor(10, 16) // equals to { r: 0, g: 64, b: 255 }

Demo

You can see a live demo at https://bouvens.github.io/number-to-color. The source code of the demo is also available.

An example of usage is Griffeath's machine.

Usage and Formats

Run in a console:

npm i number-to-color

Include and call it in a wanted way:

// with memoization
import { numberToColor } from 'number-to-color'

const tenthColorOfSixteen = numberToColor(10, 16) // equals to { r: 0, g: 64, b: 255 }
// without memoization for numbers [0, 1)
import { mapColor } from 'number-to-color/map-color'

const tenthColorOfSixteen = mapColor(10 / 16) // equals to { r: 0, g: 64, b: 255 }
// convert a color you got to hex format
import { rgbToHex } from 'number-to-color/rgbToHex'

const tenthColorOfSixteen = rgbToHex({ r: 0, g: 64, b: 255 }) // equals to '#0040ff'

numberToColor

numberToColor(number, colors, shuffled, defaultColor)

The function calculates a color for every number and memoizes these values for each quantity of colors it was called with. number should be equal to or greater than 0 but less than colors.

Arguments

NameTypeDefaultDescription
numberNumberAn integer number to convert
colorsNumberNumber of colors, colors > number
shuffledBooleanfalseIf true, shuffle memoized colors
defaultColor{ r: Number, g: Number , b: Number }{ r: 0, g: 0, b: 0 }A color to be returned for incorrect numbers

Returns

{ r: Number, g: Number, b: Number }

It's a color that corresponds to the number argument (0 <= r, g, b <= 255).

Sizes

With all dependencies, minified and gzipped:

  • require('number-to-color') 358 B
  • require('number-to-color/map-color') 172 B
  • require('number-to-color/rgbToHex') 131 B

How to Run the Demo Locally

Run in a console:

git clone git@github.com:bouvens/number-to-color.git
cd number-to-color
npm install
npm run start

Then open http://localhost:8080 in a browser.

References

  • Check out an example of usage in Greffeath Machine cellular automata: demo, source code.
  • This library is inspired by Nano ID.
1.0.0

2 years ago

0.5.0

3 years ago

0.4.1

4 years ago

0.4.0

5 years ago

0.3.0

5 years ago

0.2.0

5 years ago

0.1.0

5 years ago