有没有人知道javascript中将RGB颜色转换为HSV颜色格式的函数?
(或jQuery)
答案 0 :(得分:52)
这是一个独立的功能:
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}
答案 1 :(得分:8)
您可以使用TinyColor。
答案 2 :(得分:3)
尝试Color.js
答案 3 :(得分:2)
如果您需要/更喜欢jQuery插件,可以查看jquery-colors。
答案 4 :(得分:1)
试试这个: http://blog.crondesign.com/2011/02/actionscriptjavascript-colour-mode.html 它用于动作,但它们几乎相同,所以只需做一些调整。
答案 5 :(得分:1)
鉴于npm越来越受欢迎,我认为值得通过简单的API提及包含所有这些功能的包:
npm install 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
中回答
答案 6 :(得分:0)
尝试一下(wiki,错误analysis,更多:hsv2rgb,rgb2hsl,hsl2rgb和sl22sv):
currentCategory
// input: r,g,b in [0,1], out: h in [0,360) and s,v in [0,1]
function rgb2hsv(r,g,b)
{
let v=Math.max(r,g,b), n=v-Math.min(r,g,b);
let h= n && ((v==r) ? (g-b)/n : ((v==g) ? 2+(b-r)/n : 4+(r-g)/n));
return [60*(h<0?h+6:h), v&&n/v, v];
}
function rgb2hsv(r,g,b) {
let v=Math.max(r,g,b), n=v-Math.min(r,g,b);
let h= n && ((v==r) ? (g-b)/n : ((v==g) ? 2+(b-r)/n : 4+(r-g)/n));
return [60*(h<0?h+6:h), v&&n/v, v];
}
console.log(`rgb: (0.5,0.2,0.3) --> hsv: (${rgb2hsv(0.5,0.2,0.3)})`)
// ---------------
// UX
// ---------------
rgb= [0,0,0];
hs= [0,0,0];
let $ = x => document.querySelector(x);
let c = (x,s) => $(x).style.backgroundColor=s;
let hsv2rgb = (h,s,v, f= (n,k=(n+h/60)%6) => v - v*s*Math.max( Math.min(k,4-k,1), 0)) => [f(5),f(3),f(1)];
function changeRGB(i,e) {
rgb[i]=e.target.value/255;
hs = rgb2hsv(...rgb);
refresh();
}
function changeHS(i,e) {
hs[i]=e.target.value/(i?255:1);
rgb= hsv2rgb(...hs);
refresh();
}
function refresh() {
rr = rgb.map(x=>x*255|0).join(', ')
tr = `RGB: ${rr}`
th = `HSV: ${hs.map((x,i)=>i? (x*100).toFixed(2)+'%':x|0).join(', ')}`
$('.box').style.backgroundColor=`rgb(${rr})`;
$('.infoRGB').innerHTML=`${tr}`;
$('.infoHS').innerHTML =`${th}`;
$('#r').value=rgb[0]*255;
$('#g').value=rgb[1]*255;
$('#b').value=rgb[2]*255;
$('#h').value=hs[0];
$('#s').value=hs[1]*255;
$('#v').value=hs[2]*255;
}
refresh();
.box {
width: 50px;
height: 50px;
margin: 20px;
}
body {
display: flex;
}