RGB to HSV color in javascript? [closed]
Asked Answered
T

3

31

Does anyone know a function in javascript that converts RGB color to HSV color format?

(or jQuery)

Tound answered 5/11, 2011 at 19:59 Comment(3)
First significant result at a Google search: kourbatov.com/faq/rgb2hsv.htmKristie
I'm not sure if there is an easy way, but take a look here and its source code. It might be useful for youAttention
@RobW well now this is the first significant result on Google.Sabadilla
B
65

Here is a standalone function:

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)
    };
}

And how to use it:

console.log( rgb2hsv(60, 120, 180) );
// {h: 210, s: 66.67, v: 70.59}
Britannic answered 5/11, 2011 at 22:24 Comment(1)
this returns an object, but javascript doesn't have any native ability to interpret said object as a colorFlush
K
28

Pure JS, shortest

Try this (more: hsv2rgb, rgb2hsl, hsl2rgb and sl22sv):

// 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), c=v-Math.min(r,g,b);
  let h= c && ((v==r) ? (g-b)/c : ((v==g) ? 2+(b-r)/c : 4+(r-g)/c)); 
  return [60*(h<0?h+6:h), v&&c/v, v];
}

function rgb2hsv(r,g,b) {
  let v=Math.max(r,g,b), c=v-Math.min(r,g,b);
  let h= c && ((v==r) ? (g-b)/c : ((v==g) ? 2+(b-r)/c : 4+(r-g)/c)); 
  return [60*(h<0?h+6:h), v&&c/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;
}
<div>
<input id="r" type="range" min="0" max="255" oninput="changeRGB(0,event)">R<br>
<input id="g" type="range" min="0" max="255" oninput="changeRGB(1,event)">G<br>
<input id="b" type="range" min="0" max="255" oninput="changeRGB(2,event)">B<br>
<pre class="infoRGB"></pre>
</div> 

<div>
<div class="box hsl"></div>

</div>

<div>
<input id="h" type="range" min="0" max="360" oninput="changeHS(0,event)">H<br>
<input id="s" type="range" min="0" max="255" oninput="changeHS(1,event)">S<br>
<input id="v" type="range" min="0" max="255" oninput="changeHS(2,event)">V<br>
<pre class="infoHS"></pre><br>
</div>

This based on this formulas wiki - I made error analysis to show that results are correct

enter image description here

Kieserite answered 7/1, 2019 at 8:10 Comment(2)
should be considered that canvas or other sources gives rgb values in [0,255] also if you want to store in int8 array, half of the h values exceeds 255 and there are no values between 0 and 1 in integers.Sudiesudnor
@Sudiesudnor So do a little math to make them fit.Symphysis
B
1

Given the rising popularity of npm I think it is worth to mention a package containing all this functions through a simple API:

npm install colorsys

var colorsys = require('colorsys')
colorsys.rgb_to_hsv({ r: 255, g: 255, b: 255 })
// { h: 0 , s: 0 , v: 100 }

For the browser: <script src="http://netbeast.github.io/colorsys/browser.js"></script>

colorsys.rgb_to_hex(h, s, v)
// #hexcolor

https://www.npmjs.com/package/colorsys

As I answered in Javascript convert HSB/HSV color to RGB accurately

Bloated answered 12/2, 2016 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.