Last Updated: February 25, 2016
·
881
· joakley77

Dynamic Color Schemes with ChromaJS

I've come across a few projects that required some forethought into how a site owner might pick and choose colors for product x/y/z. My first thought in solving the problem was to limit the colors available to the user and only allowing them colors I deemed pleasing. As much as I wanted to do this it would require too much long term interaction on my part as the site grew and honestly, I didn't want to support this. That's where ChromaJS came into play.

From this point, all I had to do was allow the user to choose any base color they wish. Now I can manipulate it quite easily with ChromaJS like this:

<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>

<script type="text/javascript">
    var base    = '#C3544E',
        dark    = chroma( base ).darker(),
        light   = chroma( base ).lighten(),
        saturated   = chroma( base ).saturate();

    $( '.box1' ).css( 'background', dark.hex() );
    $( '.box2' ).css( 'background', light.hex() );
    $( '.box3' ).css( 'background', saturated.hex() );
</script>

What was real cool (to me) is I could also randomize color schemes depending on a few preset colors on each mouseover.

<script type="text/javascript">
    var chromaScale = chroma.scale( [ '#8032D4', '#F11150', '#B4A81D' ] ).out( 'hex' ).correctLightness( true );

    $( '.box' ).hover( function( e ) {
        var $this   = $( e.currentTarget ),
            color   = chromaScale( ( Math.random() * ( 0.000 - 1.0000 ) + 1.0000 ).toFixed( 4 ) );

        $this.attr( 'style', 'background:' + color + ';' );
    }, 
    function( e ) {
        $( e.currentTarget ).removeAttr( 'style' );
    });
</script>