Some color functions in JavaScript
This is just something I needed for my work last week. It is a small library with some basic functions to work with web colors. The script calculates lighter and darker versions from a base color.
The HTML
<h1>Color shades</h1>
<label for="baseColor">Base color: </label><input id="baseColor" value="cc0000"/> <button onclick="getShades()">Shades</button>
<div id="out"></div>
The color library
var G={},$=function(a){return document.getElementById(a)}
G.color={
rgb:function(a){
var o=a.toLowerCase()
return[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4),16)]
},
shade:function(a,b){
var v=[],i
for(i=0;i<3;i++){
v[i]=Math.round(a[i]*b)
if(v[i]>255)v[i]=255
if(v[i]<0)v[i]=0
}
return v
},
hex:function(a){var f=G.color._hex;return f(a[0])+f(a[1])+f(a[2])},
_hex:function(a){return ('0'+a.toString(16)).slice(-2)}
}
The code to do the conversion
function getShades(){
var m=G.color,cc,v=[],n,dark,lite
cc=$('baseColor').value
if(cc.length<6){
alert('Value must be a 6 character hex value.')
return
}
n=m.rgb(cc)
dark=m.hex(m.shade(n,0.8))
v.push('<div style="background:#'+dark+';color:#fff">Dark color: #'+dark+'</div>')
v.push('<div style="background:#'+cc+'">Normal color: #'+cc+'</div>')
lite=m.hex(m.shade(n,1.2))
v.push('<div style="background:#'+lite+'">Light color: #'+lite+'</div>')
$('out').innerHTML=v.join('\n')
}
Comments
To add a comment, log in or register as new user. It's free and safe.