RGB色空間とHSV色空間の相互変換 Javascript版 - 今日も適当ダイアリー 㧠Javascript ã§ã® RGB 㨠HSV ã®ç¸äºå¤æå¦çãæ¸ããã®ã§ãä»åº¦ã¯RGB 㨠HLSï¼HSLãHSIã¨å¼ã°ããäºãããï¼ã®ç¸äºå¤æãã¡ã¢ã
HLSè²ç©ºéã«ã¤ãã¦ã¯ HLS色空間 - Wikipedia ãªã©ãåç §ãã¦ãã ããã
RGB ãã HLSè²ç©ºéã¸ã®ã³ã³ãã¼ã
/** * RGB ã HLS ã¸å¤æãã¾ã * * @param {Number} r redå¤ â» 0ã255 ã®æ°å¤ * @param {Number} g greenå¤ â» 0ã255 ã®æ°å¤ * @param {Number} b blueå¤ â» 0ã255 ã®æ°å¤ * @return {Object} {h, l, s} â» h 㯠0ã360ã®æ°å¤ãl/s 㯠0ã1 ã®æ°å¤ */ function RGBtoHLS(r, g, b) { var h, // 0..360 l, s; // 0..1 // 0..1 ã«å¤æ r = r / 255; g = g / 255; b = b / 255; var max = Math.max(Math.max(r, g), b), min = Math.min(Math.min(r, g), b); // hue ã®è¨ç® if (max == min) { h = 0; // æ¬æ¥ã¯å®ç¾©ãããªãããä»®ã«0ãä»£å ¥ } else if (max == r) { h = 60 * (g - b) / (max - min) + 0; } else if (max == g) { h = (60 * (b - r) / (max - min)) + 120; } else { h = (60 * (r - g) / (max - min)) + 240; } while (h < 0) { h += 360; } // Lightness ã®è¨ç® l = (max + min) / 2; // Saturation ã®è¨ç® if (max == min) { s = 0; } else { s = (l < 0.5) ? (max - min) / (max + min) : (max - min) / (2.0 - max - min); } return {'h': h, 'l': l, 's': s, 'type': 'HLS'}; }
HLS ãã RGBè²ç©ºéã¸ã®ã³ã³ãã¼ã
/** * HLS ã RGB ã¸å¤æãã¾ã * * @param {Number} h hueå¤ â» 0ã360ã®æ°å¤ * @param {Number} l lightnesså¤ â» 0ã1 ã®æ°å¤ * @param {Number} s saturationå¤ â» 0ã1 ã®æ°å¤ * @return {Object} {r, g, b} â» r/g/b 㯠0ã255 ã®æ°å¤ */ function HLStoRGB(h, l, s) { var r, g, b; // 0..255 while (h < 0) { h += 360; } h = h % 360; // ç¹å¥ãªå ´å saturation = 0 if (s == 0) { // â RGB 㯠V ã«çãã l = Math.round(l * 255); return {'r': l, 'g': l, 'b': l, 'type': 'RGB'}; } var m2 = (l < 0.5) ? l * (1 + s) : l + s - l * s, m1 = l * 2 - m2, tmp; tmp = h + 120; if (tmp > 360) { tmp = tmp - 360 } if (tmp < 60) { r = (m1 + (m2 - m1) * tmp / 60); } else if (tmp < 180) { r = m2; } else if (tmp < 240) { r = m1 + (m2 - m1) * (240 - tmp) / 60; } else { r = m1; } tmp = h; if (tmp < 60) { g = m1 + (m2 - m1) * tmp / 60; } else if (tmp < 180) { g = m2; } else if (tmp < 240) { g = m1 + (m2 - m1) * (240 - tmp) / 60; } else { g = m1; } tmp = h - 120; if (tmp < 0) { tmp = tmp + 360 } if (tmp < 60) { b = m1 + (m2 - m1) * tmp / 60; } else if (tmp < 180) { b = m2; } else if (tmp < 240) { b = m1 + (m2 - m1) * (240 - tmp) / 60; } else { b = m1; } return {'r': Math.round(r * 255), 'g': Math.round(g * 255), 'b': Math.round(b * 255), 'type': 'RGB'}; }