Canvas color dial
by laustdeleuran
HTML
<canvas id="dial" width="300" height="300"></canvas>
CSS
canvas {
display: block;
margin: 0 auto;
border: 5px solid grey;
}
JavaScript
// Color interpolation from http://stackoverflow.com/a/11850486
function interpolate(start, end, steps, count) {
var s = start,
e = end,
final = s + (((e - s) / steps) * count);
return Math.floor(final);
}
function Color(r, g, b, a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
var hsl = this.rgbToHsl(r, g, b);
this.h = hsl[0];
this.s = hsl[1];
this.l = hsl[2];
return this;
}
Color.prototype.rgbToHsl = function(r, g, b) { // http://stackoverflow.com/a/2348659
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b),
min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0; // achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case
r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case
g:
h = (b - r) / d + 2;
break;
case
b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [Math.floor(h * 360), Math.floor(s * 100), Math.floor(l * 100)];
};
// shim layer with setTimeout fallback - https://gist.github.com/paulirish/1579671
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
////////////////////////////////////////
function DialGfx(canvas, start, end, value)...