1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】RGB HSV 相互変換 1ステートメント版

Last updated at Posted at 2022-07-10

以前 JavaScript / PHP:RGB HSV HSL 相互変換 で書いたhsv2rgbrgb2hsvをそれぞれ1文で記述してみたものです。

hsv2rgb

引数
h: 0以上360未満の浮動小数点数,
s: 0~1の浮動小数点数,
v: 0~1の浮動小数点数

戻り値
r,g,b各値(0~255)の配列

rgb2hsv

引数
r,g,b 各0~255

戻り値
h,s,vの配列

script

color_convert.js
'use strict';
const
hsv2rgb=(h,s,v)=>[5,3,1].map(n=>Math.round((v-Math.max(0,Math.min(1,2-Math.abs(2-(h/60+n)%6)))*s*v)*255)),
rgb2hsv=(r,g,b,a,i,v,d,s)=>[(s=(v=Math.max(...a=[+r,+g,+b,+r,+g]))&&(d=v-Math.min(...a))/v)&&(((a[(i=a.indexOf(v))+1]-a[i+2])/d+i*2+6)%6)*60,s,v/255];

example

  hsv2rgb(150, 0.8, 1); // [51, 255, 153]
  rgb2hsv(240, 100, 255); // [294.1935483870967, 0.6078431372549019, 1]

  hsv2rgb( ...rgb2hsv(255, 200, 95) ); // [255, 200, 95]
  rgb2hsv( ...hsv2rgb(76, 1, 1) ); // [76, 1, 1]

  // 演算の精度や丸め処理などの影響もあり、完全な可逆とはならない場合もあります。
  rgb2hsv( ...hsv2rgb(320, 0.5, 0.9) ); // [320.34782608695656, 0.5, 0.9019607843137255]

動作確認デモ

関連ページ

JavaScript / PHP: RGB HSV HSL 相互変換
input要素に対して使用可能なカラーピッカーUI

1
3
0

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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?