Note: both versions of rgbToHex
expect integer values for r
, g
and b
, so you'll need to do your own rounding if you have non-integer values.
The following will do to the RGB to hex conversion and add any required zero padding:
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…