0
0

More than 1 year has passed since last update.

JavaScriptでconstのみでのRGB-HSV相互変換関数

Last updated at Posted at 2022-07-09

RGB-HSVの色空間変換をconstのみで簡潔に書きたかった備忘録。
三項演算子を多重ネストするよりはスマートじゃないかな。

canvasのImageDataで使うの前提なのでUint8Arrayで扱えるよう、Hの範囲は180度です。
360度の場合は30->60, 180->360に置き換えます。

参考: RGBからHSVへの変換と復元

const rgb2hsv = (r,g,b) => {
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const d = max - min;
  const h = d && 30 * ({
    [r]: (g - b) / d + 6,
    [g]: (b - r) / d + 8,
    [b]: (r - g) / d + 10
  })[max] % 180;
  const s = (max - min) / max * 255;
  const v = max;
  return [h, s, v];
}

const hsv2rgb = (h,s,v) => {
  const hi = Math.floor(h/30);
  const f = h/30 - hi;
  const m = v * (1 - s/255);
  const n = v * (1 - s/255 * f);
  const k = v * (1 - s/255 * (1-f));
  const a = [v,n,m,m,k,v];
  return [a[hi%6], a[(hi+4)%6], a[(hi+2)%6]];
}
0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0