I have numbers that range from 0 to 1, and depending on this number I want a color to be made that goes from red to orange to green (#FF0000 at 0, #FF9900 at .5, #00FF00 at 1). Colors in between would be made using a gradient(http://i.imgur.com/AD9avXh.png as an example of a possible gradient).
Does my question make sense? I'll answer any questions :D
Is this possible using JavaScript?
Thanks in advance!
SOLVED! Thanks again techfoobar <3
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
function getColor(input) {
if (input > 1 || input < 0)
return "#00FFFF";
var p = context.getImageData(input * 100, 0, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
return hex;
}
var canvas = document.createElement("canvas");
canvas.id = 'myCanvas';
canvas.width = 101;
canvas.height = 1;
var context = canvas.getContext('2d');
context.rect(0, 0, canvas.width, canvas.height);
var grd = context.createLinearGradient(0, 0, canvas.width, canvas.height);
grd.addColorStop(0, '#FF0000');
grd.addColorStop(.5, '#FF9900');
grd.addColorStop(1, '#00FF00');
context.fillStyle = grd;
context.fill();
getColor() would be the method to use, works for values 0-1, anything greater than 1 or less than 0 returns cyan. To change the range you would change the width of the canvas, adjust the first if in getColor, and change the grd.addColorStop() lines accordingly