farbtastic.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. // Farbtastic 2.0.0-alpha.1
  2. // 2014 by Matt Farina
  3. // 2015 by Mario Stephan
  4. jQuery.browser = {};
  5. jQuery.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
  6. (function ($) {
  7. var __debug = false;
  8. $.fn.farbtastic = function (options) {
  9. $.farbtastic(this, options);
  10. return this;
  11. };
  12. $.farbtastic = function (container, options) {
  13. var container = $(container)[0];
  14. return container.farbtastic || (container.farbtastic = new $._farbtastic(container, options));
  15. }
  16. $._farbtastic = function (container, options) {
  17. var fb = this;
  18. /////////////////////////////////////////////////////
  19. /**
  20. * Link to the given element(s) or g.
  21. */
  22. fb.linkTo = function (callback) {
  23. // Unbind previous nodes
  24. if (typeof fb.callback == 'object') {
  25. $(fb.callback).unbind('keyup', fb.updateValue);
  26. }
  27. // Reset color
  28. fb.color = null;
  29. // Bind callback or elements
  30. if (typeof callback == 'function') {
  31. fb.callback = callback;
  32. }
  33. else if (typeof callback == 'object' || typeof callback == 'string') {
  34. fb.callback = $(callback);
  35. fb.callback.bind('keyup', fb.updateValue);
  36. if (fb.callback[0].value) {
  37. fb.setColor(fb.callback[0].value);
  38. }
  39. }
  40. return this;
  41. }
  42. fb.updateValue = function (event) {
  43. if (this.value && this.value != fb.color) {
  44. fb.setColor(this.value);
  45. }
  46. }
  47. /**
  48. * Change color with HTML syntax #123456
  49. */
  50. fb.setColor = function (color) {
  51. var unpack = fb.unpack(color);
  52. if (fb.color != color && unpack) {
  53. fb.color = color;
  54. fb.rgb = unpack;
  55. fb.hsl = fb.RGBToHSL(fb.rgb);
  56. fb.updateDisplay();
  57. }
  58. return this;
  59. }
  60. /**
  61. * Change color with HSL triplet [0..1, 0..1, 0..1]
  62. */
  63. fb.setHSL = function (hsl) {
  64. fb.hsl = hsl;
  65. fb.rgb = fb.HSLToRGB(hsl);
  66. fb.color = fb.pack(fb.rgb);
  67. fb.updateDisplay();
  68. return this;
  69. }
  70. /////////////////////////////////////////////////////
  71. /**
  72. * Initialize the color picker widget.
  73. */
  74. fb.initWidget = function () {
  75. // Insert markup and size accordingly.
  76. var dim = {
  77. width: options.width,
  78. height: options.width
  79. };
  80. $(container)
  81. .html(
  82. '<div class="farbtastic" style="position: relative">' +
  83. '<div class="farbtastic-solid"></div>' +
  84. '<canvas class="farbtastic-mask"></canvas>' +
  85. '<canvas class="farbtastic-overlay"></canvas>' +
  86. '</div>'
  87. )
  88. .find('*').attr(dim).css(dim).end()
  89. .find('div>*').css('position', 'absolute');
  90. // IE Fix: Recreate canvas elements with doc.createElement and excanvas.
  91. $.browser.msie || false && $('canvas', container).each(function () {
  92. // Fetch info.
  93. var attr = { 'class': $(this).attr('class'), style: this.getAttribute('style') },
  94. e = document.createElement('canvas');
  95. // Replace element.
  96. $(this).before($(e).attr(attr)).remove();
  97. // Init with explorerCanvas.
  98. G_vmlCanvasManager && G_vmlCanvasManager.initElement(e);
  99. // Set explorerCanvas elements dimensions and absolute positioning.
  100. $(e).attr(dim).css(dim).css('position', 'absolute')
  101. .find('*').attr(dim).css(dim);
  102. });
  103. // Determine layout
  104. fb.radius = (options.width - options.wheelWidth) / 2 - 1;
  105. fb.square = Math.floor((fb.radius - options.wheelWidth / 2) * 0.7) - 1;
  106. fb.mid = Math.floor(options.width / 2);
  107. fb.markerSize = options.wheelWidth * 0.3;
  108. fb.solidFill = $('.farbtastic-solid', container).css({
  109. width: fb.square * 2 - 1,
  110. height: fb.square * 2 - 1,
  111. left: fb.mid - fb.square,
  112. top: fb.mid - fb.square
  113. });
  114. // Set up drawing context.
  115. fb.cnvMask = $('.farbtastic-mask', container);
  116. fb.ctxMask = fb.cnvMask[0].getContext('2d');
  117. fb.cnvOverlay = $('.farbtastic-overlay', container);
  118. fb.ctxOverlay = fb.cnvOverlay[0].getContext('2d');
  119. fb.ctxMask.translate(fb.mid, fb.mid);
  120. fb.ctxOverlay.translate(fb.mid, fb.mid);
  121. // Draw widget base layers.
  122. fb.drawCircle();
  123. fb.drawMask();
  124. }
  125. /**
  126. * Draw the color wheel.
  127. */
  128. fb.drawCircle = function () {
  129. var tm = +(new Date());
  130. // Draw a hue circle with a bunch of gradient-stroked beziers.
  131. // Have to use beziers, as gradient-stroked arcs don't work.
  132. var n = 24,
  133. r = fb.radius,
  134. w = options.wheelWidth,
  135. nudge = 8 / r / n * Math.PI, // Fudge factor for seams.
  136. m = fb.ctxMask,
  137. angle1 = 0, color1, d1;
  138. m.save();
  139. m.lineWidth = w / r;
  140. m.scale(r, r);
  141. // Each segment goes from angle1 to angle2.
  142. for (var i = 0; i <= n; ++i) {
  143. var d2 = i / n,
  144. angle2 = d2 * Math.PI * 2,
  145. // Endpoints
  146. x1 = Math.sin(angle1), y1 = -Math.cos(angle1);
  147. x2 = Math.sin(angle2), y2 = -Math.cos(angle2),
  148. // Midpoint chosen so that the endpoints are tangent to the circle.
  149. am = (angle1 + angle2) / 2,
  150. tan = 1 / Math.cos((angle2 - angle1) / 2),
  151. xm = Math.sin(am) * tan, ym = -Math.cos(am) * tan,
  152. // New color
  153. color2 = fb.pack(fb.HSLToRGB([d2, 1, 0.5]));
  154. if (i > 0) {
  155. if ($.browser.msie || false) {
  156. // IE's gradient calculations mess up the colors. Correct along the diagonals.
  157. var corr = (1 + Math.min(Math.abs(Math.tan(angle1)), Math.abs(Math.tan(Math.PI / 2 - angle1)))) / n;
  158. color1 = fb.pack(fb.HSLToRGB([d1 - 0.15 * corr, 1, 0.5]));
  159. color2 = fb.pack(fb.HSLToRGB([d2 + 0.15 * corr, 1, 0.5]));
  160. // Create gradient fill between the endpoints.
  161. var grad = m.createLinearGradient(x1, y1, x2, y2);
  162. grad.addColorStop(0, color1);
  163. grad.addColorStop(1, color2);
  164. m.fillStyle = grad;
  165. // Draw quadratic curve segment as a fill.
  166. var r1 = (r + w / 2) / r, r2 = (r - w / 2) / r; // inner/outer radius.
  167. m.beginPath();
  168. m.moveTo(x1 * r1, y1 * r1);
  169. m.quadraticCurveTo(xm * r1, ym * r1, x2 * r1, y2 * r1);
  170. m.lineTo(x2 * r2, y2 * r2);
  171. m.quadraticCurveTo(xm * r2, ym * r2, x1 * r2, y1 * r2);
  172. m.fill();
  173. }
  174. else {
  175. // Create gradient fill between the endpoints.
  176. var grad = m.createLinearGradient(x1, y1, x2, y2);
  177. grad.addColorStop(0, color1);
  178. grad.addColorStop(1, color2);
  179. m.strokeStyle = grad;
  180. // Draw quadratic curve segment.
  181. m.beginPath();
  182. m.moveTo(x1, y1);
  183. m.quadraticCurveTo(xm, ym, x2, y2);
  184. m.stroke();
  185. }
  186. }
  187. // Prevent seams where curves join.
  188. angle1 = angle2 - nudge; color1 = color2; d1 = d2;
  189. }
  190. m.restore();
  191. __debug && $('body').append('<div>drawCircle '+ (+(new Date()) - tm) +'ms');
  192. };
  193. /**
  194. * Draw the saturation/luminance mask.
  195. */
  196. fb.drawMask = function () {
  197. var tm = +(new Date());
  198. // Iterate over sat/lum space and calculate appropriate mask pixel values.
  199. var size = fb.square * 2, sq = fb.square;
  200. function calculateMask(sizex, sizey, outputPixel) {
  201. var isx = 1 / sizex, isy = 1 / sizey;
  202. for (var y = 0; y <= sizey; ++y) {
  203. var l = 1 - y * isy;
  204. for (var x = 0; x <= sizex; ++x) {
  205. var s = 1 - x * isx;
  206. // From sat/lum to alpha and color (grayscale)
  207. var a = 1 - 2 * Math.min(l * s, (1 - l) * s);
  208. var c = (a > 0) ? ((2 * l - 1 + a) * .5 / a) : 0;
  209. outputPixel(x, y, c, a);
  210. }
  211. }
  212. }
  213. // Method #1: direct pixel access (new Canvas).
  214. // #1 disabled due to problems on tablet screen
  215. if (fb.ctxMask.getImageData && false) {
  216. // Create half-resolution buffer.
  217. var sz = Math.floor(size / 2);
  218. var buffer = document.createElement('canvas');
  219. buffer.width = buffer.height = sz + 1;
  220. var ctx = buffer.getContext('2d');
  221. var frame = ctx.getImageData(0, 0, sz + 1, sz + 1);
  222. var i = 0;
  223. calculateMask(sz, sz, function (x, y, c, a) {
  224. frame.data[i++] = frame.data[i++] = frame.data[i++] = c * 255;
  225. frame.data[i++] = a * 255;
  226. });
  227. ctx.putImageData(frame, 0, 0);
  228. fb.ctxMask.drawImage(buffer, 0, 0, sz + 1, sz + 1, -sq, -sq, sq * 2, sq * 2);
  229. }
  230. // Method #2: drawing commands (old Canvas).
  231. else if (!($.browser.msie || false)) {
  232. // Render directly at half-resolution
  233. var sz = Math.floor(size / 2);
  234. calculateMask(sz, sz, function (x, y, c, a) {
  235. c = Math.round(c * 255);
  236. fb.ctxMask.fillStyle = 'rgba(' + c + ', ' + c + ', ' + c + ', ' + a +')';
  237. fb.ctxMask.fillRect(x * 2 - sq - 1, y * 2 - sq - 1, 2, 2);
  238. });
  239. }
  240. // Method #3: vertical DXImageTransform gradient strips (IE).
  241. else {
  242. var cache_last, cache, w = 6; // Each strip is 6 pixels wide.
  243. var sizex = Math.floor(size / w);
  244. // 6 vertical pieces of gradient per strip.
  245. calculateMask(sizex, 6, function (x, y, c, a) {
  246. if (x == 0) {
  247. cache_last = cache;
  248. cache = [];
  249. }
  250. c = Math.round(c * 255);
  251. a = Math.round(a * 255);
  252. // We can only start outputting gradients once we have two rows of pixels.
  253. if (y > 0) {
  254. var c_last = cache_last[x][0],
  255. a_last = cache_last[x][1],
  256. color1 = fb.packDX(c_last, a_last),
  257. color2 = fb.packDX(c, a),
  258. y1 = Math.round(fb.mid + ((y - 1) * .333 - 1) * sq),
  259. y2 = Math.round(fb.mid + (y * .333 - 1) * sq);
  260. $('<div>').css({
  261. position: 'absolute',
  262. filter: "progid:DXImageTransform.Microsoft.Gradient(StartColorStr="+ color1 +", EndColorStr="+ color2 +", GradientType=0)",
  263. top: y1,
  264. height: y2 - y1,
  265. // Avoid right-edge sticking out.
  266. left: fb.mid + (x * w - sq - 1),
  267. width: w - (x == sizex ? Math.round(w / 2) : 0)
  268. }).appendTo(fb.cnvMask);
  269. }
  270. cache.push([c, a]);
  271. });
  272. }
  273. __debug && $('body').append('<div>drawMask '+ (+(new Date()) - tm) +'ms');
  274. }
  275. /**
  276. * Draw the selection markers.
  277. */
  278. fb.drawMarkers = function () {
  279. // Determine marker dimensions
  280. var sz = options.width, lw = Math.ceil(fb.markerSize / 4), r = fb.markerSize - lw + 1;
  281. var angle = fb.hsl[0] * 6.28,
  282. x1 = Math.sin(angle) * fb.radius,
  283. y1 = -Math.cos(angle) * fb.radius,
  284. x2 = 2 * fb.square * (.5 - fb.hsl[1]),
  285. y2 = 2 * fb.square * (.5 - fb.hsl[2]),
  286. c1 = fb.invert ? '#fff' : '#000',
  287. c2 = fb.invert ? '#000' : '#fff';
  288. var circles = [
  289. { x: x1, y: y1, r: r, c: '#000', lw: lw + 1 },
  290. { x: x1, y: y1, r: fb.markerSize, c: '#fff', lw: lw },
  291. { x: x2, y: y2, r: r, c: c2, lw: lw + 1 },
  292. { x: x2, y: y2, r: fb.markerSize, c: c1, lw: lw },
  293. ];
  294. // Update the overlay canvas.
  295. fb.ctxOverlay.clearRect(-fb.mid, -fb.mid, sz, sz);
  296. for (var i = 0; i < circles.length; i++) {
  297. var c = circles[i];
  298. fb.ctxOverlay.lineWidth = c.lw;
  299. fb.ctxOverlay.strokeStyle = c.c;
  300. fb.ctxOverlay.beginPath();
  301. fb.ctxOverlay.arc(c.x, c.y, c.r, 0, Math.PI * 2, true);
  302. fb.ctxOverlay.stroke();
  303. }
  304. }
  305. /**
  306. * Update the markers and styles
  307. */
  308. fb.updateDisplay = function () {
  309. // Determine whether labels/markers should invert.
  310. fb.invert = (fb.rgb[0] * 0.3 + fb.rgb[1] * .59 + fb.rgb[2] * .11) <= 0.6;
  311. // Update the solid background fill.
  312. fb.solidFill.css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5])));
  313. // Draw markers
  314. fb.drawMarkers();
  315. // Linked elements or callback
  316. if (typeof fb.callback == 'object') {
  317. // Set background/foreground color
  318. $(fb.callback).css({
  319. backgroundColor: fb.color,
  320. color: fb.invert ? '#fff' : '#000'
  321. });
  322. // Change linked value
  323. $(fb.callback).each(function() {
  324. if ((typeof this.value == 'string') && this.value != fb.color) {
  325. this.value = fb.color;
  326. }
  327. }).change();
  328. }
  329. else if (typeof fb.callback == 'function') {
  330. fb.callback.call(fb, fb.color);
  331. }
  332. }
  333. /**
  334. * Helper for returning coordinates relative to the center.
  335. */
  336. fb.widgetCoords = function (event) {
  337. var e = event.originalEvent;
  338. var eX = e.touches ? e.touches[0].clientX :event.pageX;
  339. var eY = e.touches ? e.touches[0].clientY :event.pageY;
  340. return {
  341. x: eX - fb.offset.left - fb.mid,
  342. y: eY - fb.offset.top - fb.mid
  343. };
  344. }
  345. /**
  346. * Mousedown handler
  347. */
  348. fb.mousedown = function (event) {
  349. // Capture mouse
  350. if (!$._farbtastic.dragging) {
  351. var moveEventType=((document.ontouchmove!==null)?'mousemove':'touchmove');
  352. var releaseEventType=((document.ontouchend!==null)?'mouseup':'touchend');
  353. $(document).bind(moveEventType, fb.mousemove).bind(releaseEventType, fb.mouseup);
  354. $._farbtastic.dragging = true;
  355. }
  356. // Update the stored offset for the widget.
  357. fb.offset = $(this).offset();
  358. // Check which area is being dragged
  359. var pos = fb.widgetCoords(event);
  360. fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) > (fb.square + 2);
  361. // Process
  362. fb.mousemove(event);
  363. return false;
  364. }
  365. /**
  366. * Mousemove handler
  367. */
  368. fb.mousemove = function (event) {
  369. // Get coordinates relative to color picker center
  370. var pos = fb.widgetCoords(event);
  371. if (!fb.color) fb.setHSL([1,1,1]);
  372. // Set new HSL parameters
  373. if (fb.circleDrag) {
  374. var hue = Math.atan2(pos.x, -pos.y) / 6.28;
  375. fb.setHSL([(hue + 1) % 1, fb.hsl[1], fb.hsl[2]]);
  376. }
  377. else {
  378. var sat = Math.max(0, Math.min(1, -(pos.x / fb.square / 2) + .5));
  379. var lum = Math.max(0, Math.min(1, -(pos.y / fb.square / 2) + .5));
  380. fb.setHSL([fb.hsl[0], sat, lum]);
  381. }
  382. return false;
  383. }
  384. /**
  385. * Mouseup handler
  386. */
  387. fb.mouseup = function () {
  388. // Uncapture mouse
  389. var moveEventType=((document.ontouchmove!==null)?'mousemove':'touchmove');
  390. var releaseEventType=((document.ontouchend!==null)?'mouseup':'touchend');
  391. $(document).unbind(moveEventType, fb.mousemove);
  392. $(document).unbind(releaseEventType, fb.mouseup);
  393. $._farbtastic.dragging = false;
  394. // trigger release event
  395. console.log('fb.release:',typeof fb.release);
  396. if (typeof fb.release == 'function') {
  397. fb.release.call(fb, fb.color);
  398. }
  399. }
  400. /* Various color utility functions */
  401. fb.dec2hex = function (x) {
  402. return (x < 16 ? '0' : '') + x.toString(16);
  403. }
  404. fb.packDX = function (c, a) {
  405. return '#' + fb.dec2hex(a) + fb.dec2hex(c) + fb.dec2hex(c) + fb.dec2hex(c);
  406. };
  407. fb.pack = function (rgb) {
  408. var r = Math.round(rgb[0] * 255);
  409. var g = Math.round(rgb[1] * 255);
  410. var b = Math.round(rgb[2] * 255);
  411. return '#' + fb.dec2hex(r) + fb.dec2hex(g) + fb.dec2hex(b);
  412. };
  413. fb.unpack = function (color) {
  414. if (color.length == 7) {
  415. function x(i) {
  416. return parseInt(color.substring(i, i + 2), 16) / 255;
  417. }
  418. return [ x(1), x(3), x(5) ];
  419. }
  420. else if (color.length == 4) {
  421. function x(i) {
  422. return parseInt(color.substring(i, i + 1), 16) / 15;
  423. }
  424. return [ x(1), x(2), x(3) ];
  425. }
  426. };
  427. fb.HSLToRGB = function (hsl) {
  428. var m1, m2, r, g, b;
  429. var h = hsl[0], s = hsl[1], l = hsl[2];
  430. m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s;
  431. m1 = l * 2 - m2;
  432. return [
  433. this.hueToRGB(m1, m2, h + 0.33333),
  434. this.hueToRGB(m1, m2, h),
  435. this.hueToRGB(m1, m2, h - 0.33333)
  436. ];
  437. };
  438. fb.hueToRGB = function (m1, m2, h) {
  439. h = (h + 1) % 1;
  440. if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
  441. if (h * 2 < 1) return m2;
  442. if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
  443. return m1;
  444. };
  445. fb.RGBToHSL = function (rgb) {
  446. var r = rgb[0], g = rgb[1], b = rgb[2],
  447. min = Math.min(r, g, b),
  448. max = Math.max(r, g, b),
  449. delta = max - min,
  450. h = 0,
  451. s = 0,
  452. l = (min + max) / 2;
  453. if (l > 0 && l < 1) {
  454. s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
  455. }
  456. if (delta > 0) {
  457. if (max == r && max != g) h += (g - b) / delta;
  458. if (max == g && max != b) h += (2 + (b - r) / delta);
  459. if (max == b && max != r) h += (4 + (r - g) / delta);
  460. h /= 6;
  461. }
  462. return [h, s, l];
  463. };
  464. // Parse options.
  465. if (!options.callback) {
  466. options = { callback: options };
  467. }
  468. options = $.extend({
  469. width: 300,
  470. wheelWidth: (options.width || 300) / 10,
  471. callback: null,
  472. release: null,
  473. }, options);
  474. // Initialize.
  475. fb.initWidget();
  476. // Install mousedown handler (the others are set on the document on-demand)
  477. var clickEventType=((document.ontouchstart!==null)?'mousedown':'touchstart');
  478. $('canvas.farbtastic-overlay', container).bind(clickEventType,fb.mousedown);
  479. // Set linked elements/callback
  480. if (options.callback) {
  481. fb.linkTo(options.callback);
  482. }
  483. fb.release = options.release;
  484. // Set to gray.
  485. //if (!fb.color) fb.setColor('#44bbcc');
  486. }
  487. })(jQuery);