colorpicker.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /**
  2. * ColorPicker - pure JavaScript color picker without using images, external CSS or 1px divs.
  3. * Copyright © 2011 David Durman, All rights reserved.
  4. */
  5. (function(window, document, undefined) {
  6. var type = (window.SVGAngle || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML"),
  7. picker, slide, hueOffset = 15, svgNS = 'http://www.w3.org/2000/svg';
  8. // This HTML snippet is inserted into the innerHTML property of the passed color picker element
  9. // when the no-hassle call to ColorPicker() is used, i.e. ColorPicker(function(hex, hsv, rgb) { ... });
  10. var colorpickerHTMLSnippet = [
  11. '<div class="picker-wrapper">',
  12. '<div class="picker"></div>',
  13. '<div class="picker-indicator"></div>',
  14. '</div>',
  15. '<div class="slide-wrapper">',
  16. '<div class="slide"></div>',
  17. '<div class="slide-indicator"></div>',
  18. '</div>'
  19. ].join('');
  20. /**
  21. * Return mouse position relative to the element el.
  22. */
  23. function mousePosition(evt) {
  24. // IE:
  25. if (window.event && window.event.contentOverflow !== undefined) {
  26. return { x: window.event.offsetX, y: window.event.offsetY };
  27. }
  28. // Webkit:
  29. if (evt.offsetX !== undefined && evt.offsetY !== undefined) {
  30. return { x: evt.offsetX, y: evt.offsetY };
  31. }
  32. // Firefox:
  33. var wrapper = evt.target.parentNode.parentNode;
  34. return { x: evt.layerX - wrapper.offsetLeft, y: evt.layerY - wrapper.offsetTop };
  35. }
  36. /**
  37. * Create SVG element.
  38. */
  39. function $(el, attrs, children) {
  40. el = document.createElementNS(svgNS, el);
  41. for (var key in attrs)
  42. el.setAttribute(key, attrs[key]);
  43. if (Object.prototype.toString.call(children) != '[object Array]') children = [children];
  44. var i = 0, len = (children[0] && children.length) || 0;
  45. for (; i < len; i++)
  46. el.appendChild(children[i]);
  47. return el;
  48. }
  49. /**
  50. * Create slide and picker markup depending on the supported technology.
  51. */
  52. if (type == 'SVG') {
  53. slide = $('svg', { xmlns: 'http://www.w3.org/2000/svg', version: '1.1', width: '100%', height: '100%' },
  54. [
  55. $('defs', {},
  56. $('linearGradient', { id: 'gradient-hsv', x1: '0%', y1: '100%', x2: '0%', y2: '0%'},
  57. [
  58. $('stop', { offset: '0%', 'stop-color': '#FF0000', 'stop-opacity': '1' }),
  59. $('stop', { offset: '13%', 'stop-color': '#FF00FF', 'stop-opacity': '1' }),
  60. $('stop', { offset: '25%', 'stop-color': '#8000FF', 'stop-opacity': '1' }),
  61. $('stop', { offset: '38%', 'stop-color': '#0040FF', 'stop-opacity': '1' }),
  62. $('stop', { offset: '50%', 'stop-color': '#00FFFF', 'stop-opacity': '1' }),
  63. $('stop', { offset: '63%', 'stop-color': '#00FF40', 'stop-opacity': '1' }),
  64. $('stop', { offset: '75%', 'stop-color': '#0BED00', 'stop-opacity': '1' }),
  65. $('stop', { offset: '88%', 'stop-color': '#FFFF00', 'stop-opacity': '1' }),
  66. $('stop', { offset: '100%', 'stop-color': '#FF0000', 'stop-opacity': '1' })
  67. ]
  68. )
  69. ),
  70. $('rect', { x: '0', y: '0', width: '100%', height: '100%', fill: 'url(#gradient-hsv)'})
  71. ]
  72. );
  73. picker = $('svg', { xmlns: 'http://www.w3.org/2000/svg', version: '1.1', width: '100%', height: '100%' },
  74. [
  75. $('defs', {},
  76. [
  77. $('linearGradient', { id: 'gradient-black', x1: '0%', y1: '100%', x2: '0%', y2: '0%'},
  78. [
  79. $('stop', { offset: '0%', 'stop-color': '#000000', 'stop-opacity': '1' }),
  80. $('stop', { offset: '100%', 'stop-color': '#CC9A81', 'stop-opacity': '0' })
  81. ]
  82. ),
  83. $('linearGradient', { id: 'gradient-white', x1: '0%', y1: '100%', x2: '100%', y2: '100%'},
  84. [
  85. $('stop', { offset: '0%', 'stop-color': '#FFFFFF', 'stop-opacity': '1' }),
  86. $('stop', { offset: '100%', 'stop-color': '#CC9A81', 'stop-opacity': '0' })
  87. ]
  88. )
  89. ]
  90. ),
  91. $('rect', { x: '0', y: '0', width: '100%', height: '100%', fill: 'url(#gradient-white)'}),
  92. $('rect', { x: '0', y: '0', width: '100%', height: '100%', fill: 'url(#gradient-black)'})
  93. ]
  94. );
  95. } else if (type == 'VML') {
  96. slide = [
  97. '<DIV style="position: relative; width: 100%; height: 100%">',
  98. '<v:rect style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" stroked="f" filled="t">',
  99. '<v:fill type="gradient" method="none" angle="0" color="red" color2="red" colors="8519f fuchsia;.25 #8000ff;24903f #0040ff;.5 aqua;41287f #00ff40;.75 #0bed00;57671f yellow"></v:fill>',
  100. '</v:rect>',
  101. '</DIV>'
  102. ].join('');
  103. picker = [
  104. '<DIV style="position: relative; width: 100%; height: 100%">',
  105. '<v:rect style="position: absolute; left: -1px; top: -1px; width: 101%; height: 101%" stroked="f" filled="t">',
  106. '<v:fill type="gradient" method="none" angle="270" color="#FFFFFF" opacity="100%" color2="#CC9A81" o:opacity2="0%"></v:fill>',
  107. '</v:rect>',
  108. '<v:rect style="position: absolute; left: 0px; top: 0px; width: 100%; height: 101%" stroked="f" filled="t">',
  109. '<v:fill type="gradient" method="none" angle="0" color="#000000" opacity="100%" color2="#CC9A81" o:opacity2="0%"></v:fill>',
  110. '</v:rect>',
  111. '</DIV>'
  112. ].join('');
  113. if (!document.namespaces['v'])
  114. document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML');
  115. }
  116. /**
  117. * Convert HSV representation to RGB HEX string.
  118. * Credits to http://www.raphaeljs.com
  119. */
  120. function hsv2rgb(hsv) {
  121. var R, G, B, X, C;
  122. var h = (hsv.h % 360) / 60;
  123. C = hsv.v * hsv.s;
  124. X = C * (1 - Math.abs(h % 2 - 1));
  125. R = G = B = hsv.v - C;
  126. h = ~~h;
  127. R += [C, X, 0, 0, X, C][h];
  128. G += [X, C, C, X, 0, 0][h];
  129. B += [0, 0, X, C, C, X][h];
  130. var r = Math.floor(R * 255);
  131. var g = Math.floor(G * 255);
  132. var b = Math.floor(B * 255);
  133. return { r: r, g: g, b: b, hex: "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1) };
  134. }
  135. /**
  136. * Convert RGB representation to HSV.
  137. * r, g, b can be either in <0,1> range or <0,255> range.
  138. * Credits to http://www.raphaeljs.com
  139. */
  140. function rgb2hsv(rgb) {
  141. var r = rgb.r;
  142. var g = rgb.g;
  143. var b = rgb.b;
  144. if (rgb.r > 1 || rgb.g > 1 || rgb.b > 1) {
  145. r /= 255;
  146. g /= 255;
  147. b /= 255;
  148. }
  149. var H, S, V, C;
  150. V = Math.max(r, g, b);
  151. C = V - Math.min(r, g, b);
  152. H = (C == 0 ? null :
  153. V == r ? (g - b) / C + (g < b ? 6 : 0) :
  154. V == g ? (b - r) / C + 2 :
  155. (r - g) / C + 4);
  156. H = (H % 6) * 60;
  157. S = C == 0 ? 0 : C / V;
  158. return { h: H, s: S, v: V };
  159. }
  160. /**
  161. * Return click event handler for the slider.
  162. * Sets picker background color and calls ctx.callback if provided.
  163. */
  164. function slideListener(ctx, slideElement, pickerElement) {
  165. return function(evt) {
  166. evt = evt || window.event;
  167. var mouse = mousePosition(evt);
  168. ctx.h = mouse.y / slideElement.offsetHeight * 360 + hueOffset;
  169. var pickerColor = hsv2rgb({ h: ctx.h, s: 1, v: 1 });
  170. var c = hsv2rgb({ h: ctx.h, s: ctx.s, v: ctx.v });
  171. pickerElement.style.backgroundColor = pickerColor.hex;
  172. ctx.callback && ctx.callback(c.hex, { h: ctx.h - hueOffset, s: ctx.s, v: ctx.v }, { r: c.r, g: c.g, b: c.b }, undefined, mouse);
  173. }
  174. };
  175. /**
  176. * Return click event handler for the picker.
  177. * Calls ctx.callback if provided.
  178. */
  179. function pickerListener(ctx, pickerElement) {
  180. return function(evt) {
  181. evt = evt || window.event;
  182. var mouse = mousePosition(evt),
  183. width = pickerElement.offsetWidth,
  184. height = pickerElement.offsetHeight;
  185. ctx.s = mouse.x / width;
  186. ctx.v = (height - mouse.y) / height;
  187. var c = hsv2rgb(ctx);
  188. ctx.callback && ctx.callback(c.hex, { h: ctx.h - hueOffset, s: ctx.s, v: ctx.v }, { r: c.r, g: c.g, b: c.b }, mouse);
  189. }
  190. };
  191. var uniqID = 0;
  192. /**
  193. * ColorPicker.
  194. * @param {DOMElement} slideElement HSV slide element.
  195. * @param {DOMElement} pickerElement HSV picker element.
  196. * @param {Function} callback Called whenever the color is changed provided chosen color in RGB HEX format as the only argument.
  197. */
  198. function ColorPicker(slideElement, pickerElement, callback) {
  199. if (!(this instanceof ColorPicker)) return new ColorPicker(slideElement, pickerElement, callback);
  200. this.h = 0;
  201. this.s = 1;
  202. this.v = 1;
  203. if (!callback) {
  204. // call of the form ColorPicker(element, funtion(hex, hsv, rgb) { ... }), i.e. the no-hassle call.
  205. var element = slideElement;
  206. element.innerHTML = colorpickerHTMLSnippet;
  207. this.slideElement = element.getElementsByClassName('slide')[0];
  208. this.pickerElement = element.getElementsByClassName('picker')[0];
  209. var slideIndicator = element.getElementsByClassName('slide-indicator')[0];
  210. var pickerIndicator = element.getElementsByClassName('picker-indicator')[0];
  211. ColorPicker.fixIndicators(slideIndicator, pickerIndicator);
  212. this.callback = function(hex, hsv, rgb, pickerCoordinate, slideCoordinate) {
  213. ColorPicker.positionIndicators(slideIndicator, pickerIndicator, slideCoordinate, pickerCoordinate);
  214. pickerElement(hex, hsv, rgb);
  215. };
  216. } else {
  217. this.callback = callback;
  218. this.pickerElement = pickerElement;
  219. this.slideElement = slideElement;
  220. }
  221. if (type == 'SVG') {
  222. // Generate uniq IDs for linearGradients so that we don't have the same IDs within one document.
  223. // Then reference those gradients in the associated rectangles.
  224. var slideClone = slide.cloneNode(true);
  225. var pickerClone = picker.cloneNode(true);
  226. var hsvGradient = slideClone.getElementsByTagName('linearGradient')[0];
  227. var hsvRect = slideClone.getElementsByTagName('rect')[0];
  228. hsvGradient.id = 'gradient-hsv-' + uniqID;
  229. hsvRect.setAttribute('fill', 'url(#' + hsvGradient.id + ')');
  230. var blackAndWhiteGradients = [pickerClone.getElementsByTagName('linearGradient')[0], pickerClone.getElementsByTagName('linearGradient')[1]];
  231. var whiteAndBlackRects = pickerClone.getElementsByTagName('rect');
  232. blackAndWhiteGradients[0].id = 'gradient-black-' + uniqID;
  233. blackAndWhiteGradients[1].id = 'gradient-white-' + uniqID;
  234. whiteAndBlackRects[0].setAttribute('fill', 'url(#' + blackAndWhiteGradients[1].id + ')');
  235. whiteAndBlackRects[1].setAttribute('fill', 'url(#' + blackAndWhiteGradients[0].id + ')');
  236. this.slideElement.appendChild(slideClone);
  237. this.pickerElement.appendChild(pickerClone);
  238. uniqID++;
  239. } else {
  240. this.slideElement.innerHTML = slide;
  241. this.pickerElement.innerHTML = picker;
  242. }
  243. addEventListener(this.slideElement, 'click', slideListener(this, this.slideElement, this.pickerElement));
  244. addEventListener(this.pickerElement, 'click', pickerListener(this, this.pickerElement));
  245. enableDragging(this, this.slideElement, slideListener(this, this.slideElement, this.pickerElement));
  246. enableDragging(this, this.pickerElement, pickerListener(this, this.pickerElement));
  247. };
  248. function addEventListener(element, event, listener) {
  249. if (element.attachEvent) {
  250. element.attachEvent('on' + event, listener);
  251. } else if (element.addEventListener) {
  252. element.addEventListener(event, listener, false);
  253. }
  254. }
  255. /**
  256. * Enable drag&drop color selection.
  257. * @param {object} ctx ColorPicker instance.
  258. * @param {DOMElement} element HSV slide element or HSV picker element.
  259. * @param {Function} listener Function that will be called whenever mouse is dragged over the element with event object as argument.
  260. */
  261. function enableDragging(ctx, element, listener) {
  262. var mousedown = false;
  263. addEventListener(element, 'mousedown', function(evt) { mousedown = true; });
  264. addEventListener(element, 'mouseup', function(evt) { mousedown = false; });
  265. addEventListener(element, 'mouseout', function(evt) { mousedown = false; });
  266. addEventListener(element, 'mousemove', function(evt) {
  267. if (mousedown) {
  268. listener(evt);
  269. }
  270. });
  271. }
  272. ColorPicker.hsv2rgb = function(hsv) {
  273. var rgbHex = hsv2rgb(hsv);
  274. delete rgbHex.hex;
  275. return rgbHex;
  276. };
  277. ColorPicker.hsv2hex = function(hsv) {
  278. return hsv2rgb(hsv).hex;
  279. };
  280. ColorPicker.rgb2hsv = rgb2hsv;
  281. ColorPicker.rgb2hex = function(rgb) {
  282. return hsv2rgb(rgb2hsv(rgb)).hex;
  283. };
  284. ColorPicker.hex2hsv = function(hex) {
  285. return rgb2hsv(ColorPicker.hex2rgb(hex));
  286. };
  287. ColorPicker.hex2rgb = function(hex) {
  288. return { r: parseInt(hex.substr(1, 2), 16), g: parseInt(hex.substr(3, 2), 16), b: parseInt(hex.substr(5, 2), 16) };
  289. };
  290. /**
  291. * Sets color of the picker in hsv/rgb/hex format.
  292. * @param {object} ctx ColorPicker instance.
  293. * @param {object} hsv Object of the form: { h: <hue>, s: <saturation>, v: <value> }.
  294. * @param {object} rgb Object of the form: { r: <red>, g: <green>, b: <blue> }.
  295. * @param {string} hex String of the form: #RRGGBB.
  296. */
  297. function setColor(ctx, hsv, rgb, hex) {
  298. ctx.h = hsv.h % 360;
  299. ctx.s = hsv.s;
  300. ctx.v = hsv.v;
  301. var c = hsv2rgb(ctx);
  302. var mouseSlide = {
  303. y: (ctx.h * ctx.slideElement.offsetHeight) / 360,
  304. x: 0 // not important
  305. };
  306. var pickerHeight = ctx.pickerElement.offsetHeight;
  307. var mousePicker = {
  308. x: ctx.s * ctx.pickerElement.offsetWidth,
  309. y: pickerHeight - ctx.v * pickerHeight
  310. };
  311. ctx.pickerElement.style.backgroundColor = hsv2rgb({ h: ctx.h, s: 1, v: 1 }).hex;
  312. ctx.callback && ctx.callback(hex || c.hex, { h: ctx.h, s: ctx.s, v: ctx.v }, rgb || { r: c.r, g: c.g, b: c.b }, mousePicker, mouseSlide);
  313. return ctx;
  314. };
  315. /**
  316. * Sets color of the picker in hsv format.
  317. * @param {object} hsv Object of the form: { h: <hue>, s: <saturation>, v: <value> }.
  318. */
  319. ColorPicker.prototype.setHsv = function(hsv) {
  320. return setColor(this, hsv);
  321. };
  322. /**
  323. * Sets color of the picker in rgb format.
  324. * @param {object} rgb Object of the form: { r: <red>, g: <green>, b: <blue> }.
  325. */
  326. ColorPicker.prototype.setRgb = function(rgb) {
  327. return setColor(this, rgb2hsv(rgb), rgb);
  328. };
  329. /**
  330. * Sets color of the picker in hex format.
  331. * @param {string} hex Hex color format #RRGGBB.
  332. */
  333. ColorPicker.prototype.setHex = function(hex) {
  334. return setColor(this, ColorPicker.hex2hsv(hex), undefined, hex);
  335. };
  336. /**
  337. * Helper to position indicators.
  338. * @param {HTMLElement} slideIndicator DOM element representing the indicator of the slide area.
  339. * @param {HTMLElement} pickerIndicator DOM element representing the indicator of the picker area.
  340. * @param {object} mouseSlide Coordinates of the mouse cursor in the slide area.
  341. * @param {object} mousePicker Coordinates of the mouse cursor in the picker area.
  342. */
  343. ColorPicker.positionIndicators = function(slideIndicator, pickerIndicator, mouseSlide, mousePicker) {
  344. if (mouseSlide) {
  345. slideIndicator.style.top = (mouseSlide.y - slideIndicator.offsetHeight/2) + 'px';
  346. }
  347. if (mousePicker) {
  348. pickerIndicator.style.top = (mousePicker.y - pickerIndicator.offsetHeight/2) + 'px';
  349. pickerIndicator.style.left = (mousePicker.x - pickerIndicator.offsetWidth/2) + 'px';
  350. }
  351. };
  352. /**
  353. * Helper to fix indicators - this is recommended (and needed) for dragable color selection (see enabledDragging()).
  354. */
  355. ColorPicker.fixIndicators = function(slideIndicator, pickerIndicator) {
  356. pickerIndicator.style.pointerEvents = 'none';
  357. slideIndicator.style.pointerEvents = 'none';
  358. };
  359. window.ColorPicker = ColorPicker;
  360. })(window, window.document);