2 * Helper functions to convert between different color formats.
4 * @author Alexander Ebert
5 * @copyright 2001-2018 WoltLab GmbH
6 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
7 * @module WoltLabSuite/Core/ColorUtil
9 define([], function () {
13 * @exports WoltLabSuite/Core/ColorUtil
17 * Converts a HSV color into RGB.
19 * @see https://secure.wikimedia.org/wikipedia/de/wiki/HSV-Farbraum#Transformation_von_RGB_und_HSV
26 hsvToRgb: function(h
, s
, v
) {
27 var rgb
= { r
: 0, g
: 0, b
: 0 };
30 h2
= Math
.floor(h
/ 60);
38 t
= v
* (1 - s
* (1 - f
));
41 rgb
.r
= rgb
.g
= rgb
.b
= v
;
85 r
: Math
.round(rgb
.r
* 255),
86 g
: Math
.round(rgb
.g
* 255),
87 b
: Math
.round(rgb
.b
* 255)
92 * Converts a RGB color into HSV.
94 * @see https://secure.wikimedia.org/wikipedia/de/wiki/HSV-Farbraum#Transformation_von_RGB_und_HSV
101 rgbToHsv: function(r
, g
, b
) {
109 max
= Math
.max(Math
.max(r
, g
), b
);
110 min
= Math
.min(Math
.min(r
, g
), b
);
117 h
= 60 * ((g
- b
) / diff
);
121 h
= 60 * (2 + (b
- r
) / diff
);
125 h
= 60 * (4 + (r
- g
) / diff
);
145 s
: Math
.round(s
* 100),
146 v
: Math
.round(v
* 100)
151 * Converts HEX into RGB.
153 * @param {string} hex
156 hexToRgb: function(hex
) {
157 if (/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(hex
)) {
158 // only convert #abc and #abcdef
159 var parts
= hex
.split('');
162 if (parts
[0] === '#') {
166 // parse shorthand #xyz
167 if (parts
.length
=== 3) {
169 r
: parseInt(parts
[0] + '' + parts
[0], 16),
170 g
: parseInt(parts
[1] + '' + parts
[1], 16),
171 b
: parseInt(parts
[2] + '' + parts
[2], 16)
176 r
: parseInt(parts
[0] + '' + parts
[1], 16),
177 g
: parseInt(parts
[2] + '' + parts
[3], 16),
178 b
: parseInt(parts
[4] + '' + parts
[5], 16)
187 * Converts a RGB into HEX.
189 * @see http://www.linuxtopia.org/online_books/javascript_guides/javascript_faq/rgbtohex.htm
196 rgbToHex: function(r
, g
, b
) {
197 var charList
= "0123456789ABCDEF";
199 if (g
=== undefined) {
200 if (r
.toString().match(/^rgba?\((\d+), ?(\d+), ?(d\+)(?:, ?[0-9.]+)?\)$/)) {
207 return (charList
.charAt((r
- r
% 16) / 16) + '' + charList
.charAt(r
% 16)) + '' + (charList
.charAt((g
- g
% 16) / 16) + '' + charList
.charAt(g
% 16)) + '' + (charList
.charAt((b
- b
% 16) / 16) + '' + charList
.charAt(b
% 16));
211 // WCF.ColorPicker compatibility (color format conversion)
212 window
.__wcf_bc_colorUtil
= ColorUtil
;