Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

javascript - RGB到十六进制和十六进制到RGB(RGB to Hex and Hex to RGB)

How to convert colors in RGB format to Hex format and vice versa?(如何将RGB格式的颜色转换为十六进制格式,反之亦然?)

For example, convert '#0080C0' to (0, 128, 192) .(例如,将'#0080C0'转换为(0, 128, 192) '#0080C0' (0, 128, 192) 。)   ask by Sindar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following will do to the RGB to hex conversion and add any required zero padding:(以下将执行RGB到十六进制的转换,并添加任何所需的零填充:)

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 Converting the other way:(转换另一种方式:) function hexToRgb(hex) { var result = /^#?([af\d]{2})([af\d]{2})([af\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } alert(hexToRgb("#0033ff").g); // "51"; Finally, an alternative version of rgbToHex() , as discussed in @casablanca's answer and suggested in the comments by @cwolves:(最后,在rgbToHex() 的答案中讨论并在@cwolves的注释中建议使用rgbToHex()的替代版本:) function rgbToHex(r, g, b) { return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); } alert(rgbToHex(0, 51, 255)); // #0033ff Update 3 December 2012(2012年12月3日更新) Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#03F":(这是hexToRgb()的一个版本,该版本还解析了一个速记十六进制三元组,例如“#03F”:) function hexToRgb(hex) { // Expand shorthand form (eg "03F") to full form (eg "0033FF") var shorthandRegex = /^#?([af\d])([af\d])([af\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([af\d]{2})([af\d]{2})([af\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } alert(hexToRgb("#0033ff").g); // "51"; alert(hexToRgb("#03f").g); // "51";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...