// ========================================================================== // Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2011 Strobe Inc. and contributors. // ©2008-2011 Apple Inc. All rights reserved. // License: Licensed under MIT license (see license.js) // ========================================================================== SC.mixin ( /** @scope SC */ { /** Returns hex color from hsv value */ convertHsvToHex: function (h, s, v) { var r = 0, g = 0, b = 0; if (v > 0) { var i = (h == 1) ? 0 : Math.floor(h * 6), f = (h == 1) ? 0 : (h * 6) - i, p = v * (1 - s), q = v * (1 - (s * f)), t = v * (1 - (s * (1 - f))), rgb = [[v,t,p],[q,v,p],[p,v,t],[p,q,v],[t,p,v],[v,p,q]]; r = Math.round(255 * rgb[i][0]); g = Math.round(255 * rgb[i][1]); b = Math.round(255 * rgb[i][2]); } return this.parseColor('rgb(' + r + ',' + g + ',' + b + ')'); }, /** Returns hsv color from hex value */ convertHexToHsv: function (hex) { var rgb = this.expandColor(hex), max = Math.max(Math.max(rgb[0], rgb[1]), rgb[2]), min = Math.min(Math.min(rgb[0], rgb[1]), rgb[2]), s = (max === 0) ? 0 : (1 - min/max), v = max/255, h = (max == min) ? 0 : ((max == rgb[0]) ? ((rgb[1]-rgb[2])/(max-min)/6) : ((max == rgb[1]) ? ((rgb[2]-rgb[0])/(max-min)/6+1/3) : ((rgb[0]-rgb[1])/(max-min)/6+2/3))); h = (h < 0) ? (h + 1) : ((h > 1) ? (h - 1) : h); return [h, s, v]; }, /** regular expression for parsing color: rgb, hex */ PARSE_COLOR_RGBRE: /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i, PARSE_COLOR_HEXRE: /^\#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, // return an array of r,g,b colour expandColor: function(color) { var hexColor, red, green, blue; hexColor = this.parseColor(color); if (hexColor) { red = parseInt(hexColor.slice(1, 3), 16); green = parseInt(hexColor.slice(3, 5), 16); blue = parseInt(hexColor.slice(5, 7), 16); return [red,green,blue]; } }, // parse rgb color or 3-digit hex color to return a properly formatted 6-digit hex colour spec, or false parseColor: function(string) { var i=0, color = '#', match, part; if(match = this.PARSE_COLOR_RGBRE.exec(string)) { for (i=1; i<=3; i++) { part = Math.max(0, Math.min(255, parseInt(match[i],0))); color += this.toColorPart(part); } return color; } if (match = this.PARSE_COLOR_HEXRE.exec(string)) { if(match[1].length == 3) { for (i=0; i<3; i++) { color += match[1].charAt(i) + match[1].charAt(i); } return color; } return '#' + match[1]; } return false; }, // convert one r,g,b number to a 2 digit hex string toColorPart: function(number) { if (number > 255) number = 255; var digits = number.toString(16); if (number < 16) return '0' + digits; return digits; } });