LoginSignup
13

More than 5 years have passed since last update.

JavaScriptでHSVからRGBに変換

Last updated at Posted at 2017-02-09

以下のようなカラーサンプルを作りたかったので、HSL and HSV(wikipedia)の計算式を参考にHSVからRGBに変換するプログラムをJavaScriptで書いてみました。

colorsample.png

実際の計算式は?

HSL and HSV(wikipedia)で公開されている計算式は以下のような感じです。

1
2
3
4
(「HSL and HSV」(5 Feb 2017, at 22:40 UTC)『ウィキペディア』より引用)

計算式中の「if 0 ≤ H' ≤ 1」の部分ですが、HSV色空間(ウィキペディア日本語版)では「if 0 ≤ H' < 1」なっていましたので、今回は「if 0 ≤ H' < 1」を使うことにしました。それがどれほどの影響を与えるのかは正直よくわかりませんが…。

HSVからRGBへの変換プログラム

hsvToRgb
function hsvToRgb(H,S,V) {
    //https://en.wikipedia.org/wiki/HSL_and_HSV#From_HSV

    var C = V * S;
    var Hp = H / 60;
    var X = C * (1 - Math.abs(Hp % 2 - 1));

    var R, G, B;
    if (0 <= Hp && Hp < 1) {[R,G,B]=[C,X,0]};
    if (1 <= Hp && Hp < 2) {[R,G,B]=[X,C,0]};
    if (2 <= Hp && Hp < 3) {[R,G,B]=[0,C,X]};
    if (3 <= Hp && Hp < 4) {[R,G,B]=[0,X,C]};
    if (4 <= Hp && Hp < 5) {[R,G,B]=[X,0,C]};
    if (5 <= Hp && Hp < 6) {[R,G,B]=[C,0,X]};

    var m = V - C;
    [R, G, B] = [R+m, G+m, B+m];

    R = Math.floor(R * 255);
    G = Math.floor(G * 255);
    B = Math.floor(B * 255);

    return [R ,G, B];
}

カラーサンプルのプログラム

実際のカラーサンプルを描くプログラムは以下のような感じです。

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 360;
canvas.height = 101;
for(var s=0;s<=100;s++) {
    for(var h=0; h<=359; h++){
        ctx.fillStyle = 'rgb(' + hsvToRgb(h, s/100, 1).join(",") + ')';
        ctx.fillRect(h, s, 1, 1);
    }
}
document.body.appendChild(canvas);

関連リンク

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
13