有谁知道javascript中将RGB颜色转换为HSV颜色格式的函数?
(或jQuery)
有谁知道javascript中将RGB颜色转换为HSV颜色格式的函数?
(或jQuery)
这是一个独立的函数:
function rgb2hsv (r, g, b) {
let rabs, gabs, babs, rr, gg, bb, h, s, v, diff, diffc, percentRoundFn;
rabs = r / 255;
gabs = g / 255;
babs = b / 255;
v = Math.max(rabs, gabs, babs),
diff = v - Math.min(rabs, gabs, babs);
diffc = c => (v - c) / 6 / diff + 1 / 2;
percentRoundFn = num => Math.round(num * 100) / 100;
if (diff == 0) {
h = s = 0;
} else {
s = diff / v;
rr = diffc(rabs);
gg = diffc(gabs);
bb = diffc(babs);
if (rabs === v) {
h = bb - gg;
} else if (gabs === v) {
h = (1 / 3) + rr - bb;
} else if (babs === v) {
h = (2 / 3) + gg - rr;
}
if (h < 0) {
h += 1;
}else if (h > 1) {
h -= 1;
}
}
return {
h: Math.round(h * 360),
s: percentRoundFn(s * 100),
v: percentRoundFn(v * 100)
};
}
以及如何使用它:
console.log( rgb2hsv(60, 120, 180) );
// {h: 210, s: 66.67, v: 70.59}
鉴于 npm 越来越流行,我认为值得一提的是一个通过简单 API 包含所有这些功能的包:
npm 安装 colorsys
var colorsys = require('colorsys')
colorsys.rgb_to_hsv({ r: 255, g: 255, b: 255 })
// { h: 0 , s: 0 , v: 100 }
对于浏览器: <script src="http://netbeast.github.io/colorsys/browser.js"></script>
colorsys.rgb_to_hex(h, s, v)
// #hexcolor
正如我在Javascript 中回答的那样准确地将 HSB/HSV 颜色转换为 RGB