Created
September 27, 2014 14:20
-
-
Save DeronW/899f2f5a4bc9ca4abac3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 16进制色值转换成rgba | |
function HEX2RGB(HEX, opacity){ | |
opacity=opacity || "1.0"; | |
HEX = HEX.replace("#",""); | |
var r = parseInt(HEX.substring(0,2),16); | |
var g = parseInt(HEX.substring(2,4),16); | |
var b = parseInt(HEX.substring(4,6),16); | |
return "rgba("+r+","+g+","+b+","+opacity+")"; | |
} | |
// rgba色值转换成16进制以及透明度 | |
function HSV2RGB(h, s, v, opacity){ | |
// inputs h=hue=0-360, s=saturation=0-1, v=value=0-1 | |
// algorithm from Wikipedia on HSV conversion | |
var toHex = function(decimalValue, places){ | |
if(places == undefined || isNaN(places)) places = 2; | |
var hex = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"); | |
var next = 0; | |
var hexidecimal = ""; | |
decimalValue=Math.floor(decimalValue); | |
while(decimalValue > 0){ | |
next = decimalValue % 16; | |
decimalValue = Math.floor((decimalValue - next)/16); | |
hexidecimal = hex[next] + hexidecimal; | |
} | |
while (hexidecimal.length < places){ | |
hexidecimal = "0"+hexidecimal; | |
} | |
return hexidecimal; | |
} | |
var hi = Math.floor(h / 60) % 6; | |
var f = h / 60 - Math.floor(h / 60); | |
var p = v * (1 - s); | |
var q = v * (1 - f * s); | |
var t = v * (1 - (1 - f) * s); | |
var r = v; // case hi==0 below | |
var g = t; | |
var b = p; | |
switch(hi){ | |
case 1: r = q; g=v; b=p; break; | |
case 2: r = p; g=v; b=t; break; | |
case 3: r = p; g=q; b=v; break; | |
case 4: r = t; g=p; b=v; break; | |
case 5: r = v; g=p; b=q; break; | |
} | |
// At this point r,g,b are in 0...1 range. Now convert into rgba or #FFFFFF notation | |
if(opacity){ | |
return "rgba(" + Math.round(255*r) + "," + Math.round(255 * g) + "," + Math.round(255 * b) + "," + opacity + ")"; | |
}else{ | |
return "#" + toHex(r * 255) + toHex(g * 255) + toHex(b * 255); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment