More colors (chroma.js)

On the weekend I wanted to try out adding colors by name and some color methods I have become accustomed to (like lighten, darken, or color blending) to my BabylonJS project. I came across a powerful lightweight library chroma.js that allows those features and all named colors from the W3CX11 spec (chroma.js api docs!).

Here’s the basic code needed:

import chroma, { Color } from 'chroma-js'

// if chroma can handle/convert this value
accept(newProp) {
  return (typeof(newProp) === 'string' && chroma.valid(newProp)) || newProp instanceof Color;

process(newProp) {
  let newColor;
  if (typeof(newProp) === 'string') {
      newColor = chroma(newProp).rgb();
  } else {
      newColor = newProp.rgb();

  return Color3.FromInts(newColor[0], newColor[1], newColor[2])

You could put those in a helper function easily to assign colors like material.diffuseColor=getColor('hotpink')

I could cheat a little bit with my implementation, because I always know when a Color3 property is being assigned from inspecting BabylonJS typings (.d.ts files), so I added a hook that detects when Color3 types are being assigned and can declaratively go like this:
<standardMaterial diffuseColor='hotpink' />

I created a running demo - there are no shadows - I am just using chroma-js to scale the color between ‘white’ and ‘black’. I also look at the luminance of the color to determine if the text should be black or white for contrast to be readable on the GUI rectangle.

Here is the demo, but all the code you need is above:

The demo uses these named colors:

['red', 'orange', 'purple', 'hotpink', 'yellow', 'chartreuse', 'olive', 'turquoise', 'navy']