Tuesday, June 4, 2013

a JavaScript Color class

I was toying around with colors in JavaScript awhile back to facilitate some color blending in my little ASCII Monsters mini-game. The class is pretty small and simple, providing only a few basic, but very helpful operations. And having run into a question or two in some development forums, it occurred to me that some of these color operations might be helpful!

So, the Color class is here:

    http://www.thepointless.com/js/color.js

At the time of this posting, I don't have any hot-link protection in place. But, I'd strongly suggest grabbing a copy of the file for yourself anyway. I can't promise the link above will remain static!

Usage is pretty simple. When you instantiate a new Color, you can either provide RGB values or a CSS-like RGB, hex, or HSL string.

// full-on red
var red = new Color(255, 0, 0);

// full-on green
var green = new Color("#00ff00");

// full-on blue
var blue = new Color("rgb(0,0,255)");

// full-on yellow, I think
var yellow_i_think = new Color("hsl(60,100%,50%)");


And we can blend colors, like so:

// the orange halfway between red and yellow
var orange = red.getBlendedColor(yellow, 0.5);

// a yellow-leaning orange
var yellow_orange = red.getBlendedColor(yellow, 0.75);

// a red-leaning orange
var red_orange = red.getBlendedColor(yellow, 0.25);


And assign these colors to and from node styles with ease:

// the Color's toString() returns a CSS-style hex string
ugly_node.style.color = red;
ugly_node.style.backgroundColor = green;


We can also create colors from node styles with ease:

// lighten ugly-node a bit
var fg = new Color(ugly_node.style.color);
var bg = new Color(ugly_node.style.backgroundColor);
ugly_node.style.color = fg.getBlendedColor(new Color('#ffffff'), 0.5);
ugly_node.style.backgroundColor = bg.getBlendedColor(new Color('#ffffff'), 0.5);


And most importantly, of course, we can make pretty gradients without leveraging technologies that don't yet have "full" cross-browser support:

<div id='gradient' style='height: 40px; width: 500px;'></div>
<script type='text/javascript'>
  (function() {
    var out = document.getElementById('gradient');
    var left = new Color("#ff0000");
    var right = new Color(255, 255, 0);
    for (var pct = 0; pct <= 1; pct += 0.01) {
      var n = document.createElement('div');
      n.style.float = 'left';
      n.style.width = '5px';
      n.style.height = '40px';
      n.style.backgroundColor = left.getBlendedColor(right, pct);
      out.appendChild(n);
    }
  })();
</script>


Case in point:


Your comments and suggestions are welcome.

4 comments: