Debian Codegraph @

closure-library/closure/goog/color/color.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Utilities related to color and color conversion.
17 */
18
19 goog.provide('goog.color');
20 goog.provide('goog.color.Hsl');
21 goog.provide('goog.color.Hsv');
22 goog.provide('goog.color.Rgb');
23
24 goog.require('goog.color.names');
25 goog.require('goog.math');
26
27
28 /**
29 * RGB color representation. An array containing three elements [r, g, b],
30 * each an integer in [0, 255], representing the red, green, and blue components
31 * of the color respectively.
32 * @typedef {Array<number>}
33 */
34 goog.color.Rgb;
35
36
37 /**
38 * HSV color representation. An array containing three elements [h, s, v]:
39 * h (hue) must be an integer in [0, 360], cyclic.
40 * s (saturation) must be a number in [0, 1].
41 * v (value/brightness) must be an integer in [0, 255].
42 * @typedef {Array<number>}
43 */
44 goog.color.Hsv;
45
46
47 /**
48 * HSL color representation. An array containing three elements [h, s, l]:
49 * h (hue) must be an integer in [0, 360], cyclic.
50 * s (saturation) must be a number in [0, 1].
51 * l (lightness) must be a number in [0, 1].
52 * @typedef {Array<number>}
53 */
54 goog.color.Hsl;
55
56
57 /**
58 * Parses a color out of a string.
59 * @param {string} str Color in some format.
60 * @return {{hex: string, type: string}} 'hex' is a string containing a hex
61 * representation of the color, 'type' is a string containing the type
62 * of color format passed in ('hex', 'rgb', 'named').
63 */
64 goog.color.parse = function(str) {
65 var result = {};
66 str = String(str);
67
68 var maybeHex = goog.color.prependHashIfNecessaryHelper(str);
69 if (goog.color.isValidHexColor_(maybeHex)) {
70 result.hex = goog.color.normalizeHex(maybeHex);
71 result.type = 'hex';
72 return result;
73 } else {
74 var rgb = goog.color.isValidRgbColor_(str);
75 if (rgb.length) {
76 result.hex = goog.color.rgbArrayToHex(rgb);
77 result.type = 'rgb';
78 return result;
79 } else if (goog.color.names) {
80 var hex = goog.color.names[str.toLowerCase()];
81 if (hex) {
82 result.hex = hex;
83 result.type = 'named';
84 return result;
85 }
86 }
87 }
88 throw Error(str + ' is not a valid color string');
89 };
90
91
92 /**
93 * Determines if the given string can be parsed as a color.
94 * {@see goog.color.parse}.
95 * @param {string} str Potential color string.
96 * @return {boolean} True if str is in a format that can be parsed to a color.
97 */
98 goog.color.isValidColor = function(str) {
99 var maybeHex = goog.color.prependHashIfNecessaryHelper(str);
100 return !!(
101 goog.color.isValidHexColor_(maybeHex) ||
102 goog.color.isValidRgbColor_(str).length ||
103 goog.color.names && goog.color.names[str.toLowerCase()]);
104 };
105
106
107 /**
108 * Parses red, green, blue components out of a valid rgb color string.
109 * Throws Error if the color string is invalid.
110 * @param {string} str RGB representation of a color.
111 * {@see goog.color.isValidRgbColor_}.
112 * @return {!goog.color.Rgb} rgb representation of the color.
113 */
114 goog.color.parseRgb = function(str) {
115 var rgb = goog.color.isValidRgbColor_(str);
116 if (!rgb.length) {
117 throw Error(str + ' is not a valid RGB color');
118 }
119 return rgb;
120 };
121
122
123 /**
124 * Converts a hex representation of a color to RGB.
125 * @param {string} hexColor Color to convert.
126 * @return {string} string of the form 'rgb(R,G,B)' which can be used in
127 * styles.
128 */
129 goog.color.hexToRgbStyle = function(hexColor) {
130 return goog.color.rgbStyle_(goog.color.hexToRgb(hexColor));
131 };
132
133
134 /**
135 * Regular expression for extracting the digits in a hex color triplet.
136 * @type {RegExp}
137 * @private
138 */
139 goog.color.hexTripletRe_ = /#(.)(.)(.)/;
140
141
142 /**
143 * Normalize an hex representation of a color
144 * @param {string} hexColor an hex color string.
145 * @return {string} hex color in the format '#rrggbb' with all lowercase
146 * literals.
147 */
148 goog.color.normalizeHex = function(hexColor) {
149 if (!goog.color.isValidHexColor_(hexColor)) {
150 throw Error("'" + hexColor + "' is not a valid hex color");
151 }
152 if (hexColor.length == 4) { // of the form #RGB
153 hexColor = hexColor.replace(goog.color.hexTripletRe_, '#$1$1$2$2$3$3');
154 }
155 return hexColor.toLowerCase();
156 };
157
158
159 /**
160 * Converts a hex representation of a color to RGB.
161 * @param {string} hexColor Color to convert.
162 * @return {!goog.color.Rgb} rgb representation of the color.
163 */
164 goog.color.hexToRgb = function(hexColor) {
165 hexColor = goog.color.normalizeHex(hexColor);
166 var r = parseInt(hexColor.substr(1, 2), 16);
167 var g = parseInt(hexColor.substr(3, 2), 16);
168 var b = parseInt(hexColor.substr(5, 2), 16);
169
170 return [r, g, b];
171 };
172
173
174 /**
175 * Converts a color from RGB to hex representation.
176 * @param {number} r Amount of red, int between 0 and 255.
177 * @param {number} g Amount of green, int between 0 and 255.
178 * @param {number} b Amount of blue, int between 0 and 255.
179 * @return {string} hex representation of the color.
180 */
181 goog.color.rgbToHex = function(r, g, b) {
182 r = Number(r);
183 g = Number(g);
184 b = Number(b);
185 if (r != (r & 255) || g != (g & 255) || b != (b & 255)) {
186 throw Error('"(' + r + ',' + g + ',' + b + '") is not a valid RGB color');
187 }
188 var hexR = goog.color.prependZeroIfNecessaryHelper(r.toString(16));
189 var hexG = goog.color.prependZeroIfNecessaryHelper(g.toString(16));
190 var hexB = goog.color.prependZeroIfNecessaryHelper(b.toString(16));
191 return '#' + hexR + hexG + hexB;
192 };
193
194
195 /**
196 * Converts a color from RGB to hex representation.
197 * @param {goog.color.Rgb} rgb rgb representation of the color.
198 * @return {string} hex representation of the color.
199 */
200 goog.color.rgbArrayToHex = function(rgb) {
201 return goog.color.rgbToHex(rgb[0], rgb[1], rgb[2]);
202 };
203
204
205 /**
206 * Converts a color from RGB color space to HSL color space.
207 * Modified from {@link http://en.wikipedia.org/wiki/HLS_color_space}.
208 * @param {number} r Value of red, in [0, 255].
209 * @param {number} g Value of green, in [0, 255].
210 * @param {number} b Value of blue, in [0, 255].
211 * @return {!goog.color.Hsl} hsl representation of the color.
212 */
213 goog.color.rgbToHsl = function(r, g, b) {
214 // First must normalize r, g, b to be between 0 and 1.
215 var normR = r / 255;
216 var normG = g / 255;
217 var normB = b / 255;
218 var max = Math.max(normR, normG, normB);
219 var min = Math.min(normR, normG, normB);
220 var h = 0;
221 var s = 0;
222
223 // Luminosity is the average of the max and min rgb color intensities.
224 var l = 0.5 * (max + min);
225
226 // The hue and saturation are dependent on which color intensity is the max.
227 // If max and min are equal, the color is gray and h and s should be 0.
228 if (max != min) {
229 if (max == normR) {
230 h = 60 * (normG - normB) / (max - min);
231 } else if (max == normG) {
232 h = 60 * (normB - normR) / (max - min) + 120;
233 } else if (max == normB) {
234 h = 60 * (normR - normG) / (max - min) + 240;
235 }
236
237 if (0 < l && l <= 0.5) {
238 s = (max - min) / (2 * l);
239 } else {
240 s = (max - min) / (2 - 2 * l);
241 }
242 }
243
244 // Make sure the hue falls between 0 and 360.
245 return [Math.round(h + 360) % 360, s, l];
246 };
247
248
249 /**
250 * Converts a color from RGB color space to HSL color space.
251 * @param {goog.color.Rgb} rgb rgb representation of the color.
252 * @return {!goog.color.Hsl} hsl representation of the color.
253 */
254 goog.color.rgbArrayToHsl = function(rgb) {
255 return goog.color.rgbToHsl(rgb[0], rgb[1], rgb[2]);
256 };
257
258
259 /**
260 * Helper for hslToRgb.
261 * @param {number} v1 Helper variable 1.
262 * @param {number} v2 Helper variable 2.
263 * @param {number} vH Helper variable 3.
264 * @return {number} Appropriate RGB value, given the above.
265 * @private
266 */
267 goog.color.hueToRgb_ = function(v1, v2, vH) {
268 if (vH < 0) {
269 vH += 1;
270 } else if (vH > 1) {
271 vH -= 1;
272 }
273 if ((6 * vH) < 1) {
274 return (v1 + (v2 - v1) * 6 * vH);
275 } else if (2 * vH < 1) {
276 return v2;
277 } else if (3 * vH < 2) {
278 return (v1 + (v2 - v1) * ((2 / 3) - vH) * 6);
279 }
280 return v1;
281 };
282
283
284 /**
285 * Converts a color from HSL color space to RGB color space.
286 * Modified from {@link http://www.easyrgb.com/math.html}
287 * @param {number} h Hue, in [0, 360].
288 * @param {number} s Saturation, in [0, 1].
289 * @param {number} l Luminosity, in [0, 1].
290 * @return {!goog.color.Rgb} rgb representation of the color.
291 */
292 goog.color.hslToRgb = function(h, s, l) {
293 var r = 0;
294 var g = 0;
295 var b = 0;
296 var normH = h / 360; // normalize h to fall in [0, 1]
297
298 if (s == 0) {
299 r = g = b = l * 255;
300 } else {
301 var temp1 = 0;
302 var temp2 = 0;
303 if (l < 0.5) {
304 temp2 = l * (1 + s);
305 } else {
306 temp2 = l + s - (s * l);
307 }
308 temp1 = 2 * l - temp2;
309 r = 255 * goog.color.hueToRgb_(temp1, temp2, normH + (1 / 3));
310 g = 255 * goog.color.hueToRgb_(temp1, temp2, normH);
311 b = 255 * goog.color.hueToRgb_(temp1, temp2, normH - (1 / 3));
312 }
313
314 return [Math.round(r), Math.round(g), Math.round(b)];
315 };
316
317
318 /**
319 * Converts a color from HSL color space to RGB color space.
320 * @param {goog.color.Hsl} hsl hsl representation of the color.
321 * @return {!goog.color.Rgb} rgb representation of the color.
322 */
323 goog.color.hslArrayToRgb = function(hsl) {
324 return goog.color.hslToRgb(hsl[0], hsl[1], hsl[2]);
325 };
326
327
328 /**
329 * Helper for isValidHexColor_.
330 * @type {RegExp}
331 * @private
332 */
333 goog.color.validHexColorRe_ = /^#(?:[0-9a-f]{3}){1,2}$/i;
334
335
336 /**
337 * Checks if a string is a valid hex color. We expect strings of the format
338 * #RRGGBB (ex: #1b3d5f) or #RGB (ex: #3CA == #33CCAA).
339 * @param {string} str String to check.
340 * @return {boolean} Whether the string is a valid hex color.
341 * @private
342 */
343 goog.color.isValidHexColor_ = function(str) {
344 return goog.color.validHexColorRe_.test(str);
345 };
346
347
348 /**
349 * Helper for isNormalizedHexColor_.
350 * @type {RegExp}
351 * @private
352 */
353 goog.color.normalizedHexColorRe_ = /^#[0-9a-f]{6}$/;
354
355
356 /**
357 * Checks if a string is a normalized hex color.
358 * We expect strings of the format #RRGGBB (ex: #1b3d5f)
359 * using only lowercase letters.
360 * @param {string} str String to check.
361 * @return {boolean} Whether the string is a normalized hex color.
362 * @private
363 */
364 goog.color.isNormalizedHexColor_ = function(str) {
365 return goog.color.normalizedHexColorRe_.test(str);
366 };
367
368
369 /**
370 * Regular expression for matching and capturing RGB style strings. Helper for
371 * isValidRgbColor_.
372 * @type {RegExp}
373 * @private
374 */
375 goog.color.rgbColorRe_ =
376 /^(?:rgb)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2})\)$/i;
377
378
379 /**
380 * Checks if a string is a valid rgb color. We expect strings of the format
381 * '(r, g, b)', or 'rgb(r, g, b)', where each color component is an int in
382 * [0, 255].
383 * @param {string} str String to check.
384 * @return {!goog.color.Rgb} the rgb representation of the color if it is
385 * a valid color, or the empty array otherwise.
386 * @private
387 */
388 goog.color.isValidRgbColor_ = function(str) {
389 // Each component is separate (rather than using a repeater) so we can
390 // capture the match. Also, we explicitly set each component to be either 0,
391 // or start with a non-zero, to prevent octal numbers from slipping through.
392 var regExpResultArray = str.match(goog.color.rgbColorRe_);
393 if (regExpResultArray) {
394 var r = Number(regExpResultArray[1]);
395 var g = Number(regExpResultArray[2]);
396 var b = Number(regExpResultArray[3]);
397 if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) {
398 return [r, g, b];
399 }
400 }
401 return [];
402 };
403
404
405 /**
406 * Takes a hex value and prepends a zero if it's a single digit.
407 * Small helper method for use by goog.color and friends.
408 * @param {string} hex Hex value to prepend if single digit.
409 * @return {string} hex value prepended with zero if it was single digit,
410 * otherwise the same value that was passed in.
411 */
412 goog.color.prependZeroIfNecessaryHelper = function(hex) {
413 return hex.length == 1 ? '0' + hex : hex;
414 };
415
416
417 /**
418 * Takes a string a prepends a '#' sign if one doesn't exist.
419 * Small helper method for use by goog.color and friends.
420 * @param {string} str String to check.
421 * @return {string} The value passed in, prepended with a '#' if it didn't
422 * already have one.
423 */
424 goog.color.prependHashIfNecessaryHelper = function(str) {
425 return str.charAt(0) == '#' ? str : '#' + str;
426 };
427
428
429 /**
430 * Takes an array of [r, g, b] and converts it into a string appropriate for
431 * CSS styles.
432 * @param {goog.color.Rgb} rgb rgb representation of the color.
433 * @return {string} string of the form 'rgb(r,g,b)'.
434 * @private
435 */
436 goog.color.rgbStyle_ = function(rgb) {
437 return 'rgb(' + rgb.join(',') + ')';
438 };
439
440
441 /**
442 * Converts an HSV triplet to an RGB array. V is brightness because b is
443 * reserved for blue in RGB.
444 * @param {number} h Hue value in [0, 360].
445 * @param {number} s Saturation value in [0, 1].
446 * @param {number} brightness brightness in [0, 255].
447 * @return {!goog.color.Rgb} rgb representation of the color.
448 */
449 goog.color.hsvToRgb = function(h, s, brightness) {
450 var red = 0;
451 var green = 0;
452 var blue = 0;
453 if (s == 0) {
454 red = brightness;
455 green = brightness;
456 blue = brightness;
457 } else {
458 var sextant = Math.floor(h / 60);
459 var remainder = (h / 60) - sextant;
460 var val1 = brightness * (1 - s);
461 var val2 = brightness * (1 - (s * remainder));
462 var val3 = brightness * (1 - (s * (1 - remainder)));
463 switch (sextant) {
464 case 1:
465 red = val2;
466 green = brightness;
467 blue = val1;
468 break;
469 case 2:
470 red = val1;
471 green = brightness;
472 blue = val3;
473 break;
474 case 3:
475 red = val1;
476 green = val2;
477 blue = brightness;
478 break;
479 case 4:
480 red = val3;
481 green = val1;
482 blue = brightness;
483 break;
484 case 5:
485 red = brightness;
486 green = val1;
487 blue = val2;
488 break;
489 case 6:
490 case 0:
491 red = brightness;
492 green = val3;
493 blue = val1;
494 break;
495 }
496 }
497
498 return [Math.floor(red), Math.floor(green), Math.floor(blue)];
499 };
500
501
502 /**
503 * Converts from RGB values to an array of HSV values.
504 * @param {number} red Red value in [0, 255].
505 * @param {number} green Green value in [0, 255].
506 * @param {number} blue Blue value in [0, 255].
507 * @return {!goog.color.Hsv} hsv representation of the color.
508 */
509 goog.color.rgbToHsv = function(red, green, blue) {
510
511 var max = Math.max(Math.max(red, green), blue);
512 var min = Math.min(Math.min(red, green), blue);
513 var hue;
514 var saturation;
515 var value = max;
516 if (min == max) {
517 hue = 0;
518 saturation = 0;
519 } else {
520 var delta = (max - min);
521 saturation = delta / max;
522
523 if (red == max) {
524 hue = (green - blue) / delta;
525 } else if (green == max) {
526 hue = 2 + ((blue - red) / delta);
527 } else {
528 hue = 4 + ((red - green) / delta);
529 }
530 hue *= 60;
531 if (hue < 0) {
532 hue += 360;
533 }
534 if (hue > 360) {
535 hue -= 360;
536 }
537 }
538
539 return [hue, saturation, value];
540 };
541
542
543 /**
544 * Converts from an array of RGB values to an array of HSV values.
545 * @param {goog.color.Rgb} rgb rgb representation of the color.
546 * @return {!goog.color.Hsv} hsv representation of the color.
547 */
548 goog.color.rgbArrayToHsv = function(rgb) {
549 return goog.color.rgbToHsv(rgb[0], rgb[1], rgb[2]);
550 };
551
552
553 /**
554 * Converts an HSV triplet to an RGB array.
555 * @param {goog.color.Hsv} hsv hsv representation of the color.
556 * @return {!goog.color.Rgb} rgb representation of the color.
557 */
558 goog.color.hsvArrayToRgb = function(hsv) {
559 return goog.color.hsvToRgb(hsv[0], hsv[1], hsv[2]);
560 };
561
562
563 /**
564 * Converts a hex representation of a color to HSL.
565 * @param {string} hex Color to convert.
566 * @return {!goog.color.Hsl} hsl representation of the color.
567 */
568 goog.color.hexToHsl = function(hex) {
569 var rgb = goog.color.hexToRgb(hex);
570 return goog.color.rgbToHsl(rgb[0], rgb[1], rgb[2]);
571 };
572
573
574 /**
575 * Converts from h,s,l values to a hex string
576 * @param {number} h Hue, in [0, 360].
577 * @param {number} s Saturation, in [0, 1].
578 * @param {number} l Luminosity, in [0, 1].
579 * @return {string} hex representation of the color.
580 */
581 goog.color.hslToHex = function(h, s, l) {
582 return goog.color.rgbArrayToHex(goog.color.hslToRgb(h, s, l));
583 };
584
585
586 /**
587 * Converts from an hsl array to a hex string
588 * @param {goog.color.Hsl} hsl hsl representation of the color.
589 * @return {string} hex representation of the color.
590 */
591 goog.color.hslArrayToHex = function(hsl) {
592 return goog.color.rgbArrayToHex(goog.color.hslToRgb(hsl[0], hsl[1], hsl[2]));
593 };
594
595
596 /**
597 * Converts a hex representation of a color to HSV
598 * @param {string} hex Color to convert.
599 * @return {!goog.color.Hsv} hsv representation of the color.
600 */
601 goog.color.hexToHsv = function(hex) {
602 return goog.color.rgbArrayToHsv(goog.color.hexToRgb(hex));
603 };
604
605
606 /**
607 * Converts from h,s,v values to a hex string
608 * @param {number} h Hue, in [0, 360].
609 * @param {number} s Saturation, in [0, 1].
610 * @param {number} v Value, in [0, 255].
611 * @return {string} hex representation of the color.
612 */
613 goog.color.hsvToHex = function(h, s, v) {
614 return goog.color.rgbArrayToHex(goog.color.hsvToRgb(h, s, v));
615 };
616
617
618 /**
619 * Converts from an HSV array to a hex string
620 * @param {goog.color.Hsv} hsv hsv representation of the color.
621 * @return {string} hex representation of the color.
622 */
623 goog.color.hsvArrayToHex = function(hsv) {
624 return goog.color.hsvToHex(hsv[0], hsv[1], hsv[2]);
625 };
626
627
628 /**
629 * Calculates the Euclidean distance between two color vectors on an HSL sphere.
630 * A demo of the sphere can be found at:
631 * http://en.wikipedia.org/wiki/HSL_color_space
632 * In short, a vector for color (H, S, L) in this system can be expressed as
633 * (S*L'*cos(2*PI*H), S*L'*sin(2*PI*H), L), where L' = abs(L - 0.5), and we
634 * simply calculate the 1-2 distance using these coordinates
635 * @param {goog.color.Hsl} hsl1 First color in hsl representation.
636 * @param {goog.color.Hsl} hsl2 Second color in hsl representation.
637 * @return {number} Distance between the two colors, in the range [0, 1].
638 */
639 goog.color.hslDistance = function(hsl1, hsl2) {
640 var sl1, sl2;
641 if (hsl1[2] <= 0.5) {
642 sl1 = hsl1[1] * hsl1[2];
643 } else {
644 sl1 = hsl1[1] * (1.0 - hsl1[2]);
645 }
646
647 if (hsl2[2] <= 0.5) {
648 sl2 = hsl2[1] * hsl2[2];
649 } else {
650 sl2 = hsl2[1] * (1.0 - hsl2[2]);
651 }
652
653 var h1 = hsl1[0] / 360.0;
654 var h2 = hsl2[0] / 360.0;
655 var dh = (h1 - h2) * 2.0 * Math.PI;
656 return (hsl1[2] - hsl2[2]) * (hsl1[2] - hsl2[2]) + sl1 * sl1 + sl2 * sl2 -
657 2 * sl1 * sl2 * Math.cos(dh);
658 };
659
660
661 /**
662 * Blend two colors together, using the specified factor to indicate the weight
663 * given to the first color
664 * @param {goog.color.Rgb} rgb1 First color represented in rgb.
665 * @param {goog.color.Rgb} rgb2 Second color represented in rgb.
666 * @param {number} factor The weight to be given to rgb1 over rgb2. Values
667 * should be in the range [0, 1]. If less than 0, factor will be set to 0.
668 * If greater than 1, factor will be set to 1.
669 * @return {!goog.color.Rgb} Combined color represented in rgb.
670 */
671 goog.color.blend = function(rgb1, rgb2, factor) {
672 factor = goog.math.clamp(factor, 0, 1);
673
674 return [
675 Math.round(factor * rgb1[0] + (1.0 - factor) * rgb2[0]),
676 Math.round(factor * rgb1[1] + (1.0 - factor) * rgb2[1]),
677 Math.round(factor * rgb1[2] + (1.0 - factor) * rgb2[2])
678 ];
679 };
680
681
682 /**
683 * Adds black to the specified color, darkening it
684 * @param {goog.color.Rgb} rgb rgb representation of the color.
685 * @param {number} factor Number in the range [0, 1]. 0 will do nothing, while
686 * 1 will return black. If less than 0, factor will be set to 0. If greater
687 * than 1, factor will be set to 1.
688 * @return {!goog.color.Rgb} Combined rgb color.
689 */
690 goog.color.darken = function(rgb, factor) {
691 var black = [0, 0, 0];
692 return goog.color.blend(black, rgb, factor);
693 };
694
695
696 /**
697 * Adds white to the specified color, lightening it
698 * @param {goog.color.Rgb} rgb rgb representation of the color.
699 * @param {number} factor Number in the range [0, 1]. 0 will do nothing, while
700 * 1 will return white. If less than 0, factor will be set to 0. If greater
701 * than 1, factor will be set to 1.
702 * @return {!goog.color.Rgb} Combined rgb color.
703 */
704 goog.color.lighten = function(rgb, factor) {
705 var white = [255, 255, 255];
706 return goog.color.blend(white, rgb, factor);
707 };
708
709
710 /**
711 * Find the "best" (highest-contrast) of the suggested colors for the prime
712 * color. Uses W3C formula for judging readability and visual accessibility:
713 * http://www.w3.org/TR/AERT#color-contrast
714 * @param {goog.color.Rgb} prime Color represented as a rgb array.
715 * @param {Array<goog.color.Rgb>} suggestions Array of colors,
716 * each representing a rgb array.
717 * @return {!goog.color.Rgb} Highest-contrast color represented by an array..
718 */
719 goog.color.highContrast = function(prime, suggestions) {
720 var suggestionsWithDiff = [];
721 for (var i = 0; i < suggestions.length; i++) {
722 suggestionsWithDiff.push({
723 color: suggestions[i],
724 diff: goog.color.yiqBrightnessDiff_(suggestions[i], prime) +
725 goog.color.colorDiff_(suggestions[i], prime)
726 });
727 }
728 suggestionsWithDiff.sort(function(a, b) { return b.diff - a.diff; });
729 return suggestionsWithDiff[0].color;
730 };
731
732
733 /**
734 * Calculate brightness of a color according to YIQ formula (brightness is Y).
735 * More info on YIQ here: http://en.wikipedia.org/wiki/YIQ. Helper method for
736 * goog.color.highContrast()
737 * @param {goog.color.Rgb} rgb Color represented by a rgb array.
738 * @return {number} brightness (Y).
739 * @private
740 */
741 goog.color.yiqBrightness_ = function(rgb) {
742 return Math.round((rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000);
743 };
744
745
746 /**
747 * Calculate difference in brightness of two colors. Helper method for
748 * goog.color.highContrast()
749 * @param {goog.color.Rgb} rgb1 Color represented by a rgb array.
750 * @param {goog.color.Rgb} rgb2 Color represented by a rgb array.
751 * @return {number} Brightness difference.
752 * @private
753 */
754 goog.color.yiqBrightnessDiff_ = function(rgb1, rgb2) {
755 return Math.abs(
756 goog.color.yiqBrightness_(rgb1) - goog.color.yiqBrightness_(rgb2));
757 };
758
759
760 /**
761 * Calculate color difference between two colors. Helper method for
762 * goog.color.highContrast()
763 * @param {goog.color.Rgb} rgb1 Color represented by a rgb array.
764 * @param {goog.color.Rgb} rgb2 Color represented by a rgb array.
765 * @return {number} Color difference.
766 * @private
767 */
768 goog.color.colorDiff_ = function(rgb1, rgb2) {
769 return Math.abs(rgb1[0] - rgb2[0]) + Math.abs(rgb1[1] - rgb2[1]) +
770 Math.abs(rgb1[2] - rgb2[2]);
771 };