vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

531 lines
19 KiB

  1. let Hammer = require('../module/hammer');
  2. let hammerUtil = require('../hammerUtil');
  3. let util = require('../util');
  4. class ColorPicker {
  5. constructor(pixelRatio = 1) {
  6. this.pixelRatio = pixelRatio;
  7. this.generated = false;
  8. this.centerCoordinates = {x:289/2, y:289/2};
  9. this.r = 289 * 0.49;
  10. this.color = {r:255,g:255,b:255,a:1.0};
  11. this.hueCircle = undefined;
  12. this.initialColor = {r:255,g:255,b:255,a:1.0};
  13. this.previousColor= undefined;
  14. this.applied = false;
  15. // bound by
  16. this.updateCallback = () => {};
  17. // create all DOM elements
  18. this._create();
  19. }
  20. /**
  21. * this inserts the colorPicker into a div from the DOM
  22. * @param container
  23. */
  24. insertTo(container) {
  25. if (this.hammer !== undefined) {
  26. this.hammer.destroy();
  27. this.hammer = undefined;
  28. }
  29. this.container = container;
  30. this.container.appendChild(this.frame);
  31. this._bindHammer();
  32. this._setSize();
  33. }
  34. /**
  35. * the callback is executed on apply and save. Bind it to the application
  36. * @param callback
  37. */
  38. setCallback(callback) {
  39. if (typeof callback === 'function') {
  40. this.updateCallback = callback;
  41. }
  42. else {
  43. throw new Error("Function attempted to set as colorPicker callback is not a function.");
  44. }
  45. }
  46. _isColorString(color) {
  47. var htmlColors = {black: '#000000',navy: '#000080',darkblue: '#00008B',mediumblue: '#0000CD',blue: '#0000FF',darkgreen: '#006400',green: '#008000',teal: '#008080',darkcyan: '#008B8B',deepskyblue: '#00BFFF',darkturquoise: '#00CED1',mediumspringgreen: '#00FA9A',lime: '#00FF00',springgreen: '#00FF7F',aqua: '#00FFFF',cyan: '#00FFFF',midnightblue: '#191970',dodgerblue: '#1E90FF',lightseagreen: '#20B2AA',forestgreen: '#228B22',seagreen: '#2E8B57',darkslategray: '#2F4F4F',limegreen: '#32CD32',mediumseagreen: '#3CB371',turquoise: '#40E0D0',royalblue: '#4169E1',steelblue: '#4682B4',darkslateblue: '#483D8B',mediumturquoise: '#48D1CC',indigo: '#4B0082',darkolivegreen: '#556B2F',cadetblue: '#5F9EA0',cornflowerblue: '#6495ED',mediumaquamarine: '#66CDAA',dimgray: '#696969',slateblue: '#6A5ACD',olivedrab: '#6B8E23',slategray: '#708090',lightslategray: '#778899',mediumslateblue: '#7B68EE',lawngreen: '#7CFC00',chartreuse: '#7FFF00',aquamarine: '#7FFFD4',maroon: '#800000',purple: '#800080',olive: '#808000',gray: '#808080',skyblue: '#87CEEB',lightskyblue: '#87CEFA',blueviolet: '#8A2BE2',darkred: '#8B0000',darkmagenta: '#8B008B',saddlebrown: '#8B4513',darkseagreen: '#8FBC8F',lightgreen: '#90EE90',mediumpurple: '#9370D8',darkviolet: '#9400D3',palegreen: '#98FB98',darkorchid: '#9932CC',yellowgreen: '#9ACD32',sienna: '#A0522D',brown: '#A52A2A',darkgray: '#A9A9A9',lightblue: '#ADD8E6',greenyellow: '#ADFF2F',paleturquoise: '#AFEEEE',lightsteelblue: '#B0C4DE',powderblue: '#B0E0E6',firebrick: '#B22222',darkgoldenrod: '#B8860B',mediumorchid: '#BA55D3',rosybrown: '#BC8F8F',darkkhaki: '#BDB76B',silver: '#C0C0C0',mediumvioletred: '#C71585',indianred: '#CD5C5C',peru: '#CD853F',chocolate: '#D2691E',tan: '#D2B48C',lightgrey: '#D3D3D3',palevioletred: '#D87093',thistle: '#D8BFD8',orchid: '#DA70D6',goldenrod: '#DAA520',crimson: '#DC143C',gainsboro: '#DCDCDC',plum: '#DDA0DD',burlywood: '#DEB887',lightcyan: '#E0FFFF',lavender: '#E6E6FA',darksalmon: '#E9967A',violet: '#EE82EE',palegoldenrod: '#EEE8AA',lightcoral: '#F08080',khaki: '#F0E68C',aliceblue: '#F0F8FF',honeydew: '#F0FFF0',azure: '#F0FFFF',sandybrown: '#F4A460',wheat: '#F5DEB3',beige: '#F5F5DC',whitesmoke: '#F5F5F5',mintcream: '#F5FFFA',ghostwhite: '#F8F8FF',salmon: '#FA8072',antiquewhite: '#FAEBD7',linen: '#FAF0E6',lightgoldenrodyellow: '#FAFAD2',oldlace: '#FDF5E6',red: '#FF0000',fuchsia: '#FF00FF',magenta: '#FF00FF',deeppink: '#FF1493',orangered: '#FF4500',tomato: '#FF6347',hotpink: '#FF69B4',coral: '#FF7F50',darkorange: '#FF8C00',lightsalmon: '#FFA07A',orange: '#FFA500',lightpink: '#FFB6C1',pink: '#FFC0CB',gold: '#FFD700',peachpuff: '#FFDAB9',navajowhite: '#FFDEAD',moccasin: '#FFE4B5',bisque: '#FFE4C4',mistyrose: '#FFE4E1',blanchedalmond: '#FFEBCD',papayawhip: '#FFEFD5',lavenderblush: '#FFF0F5',seashell: '#FFF5EE',cornsilk: '#FFF8DC',lemonchiffon: '#FFFACD',floralwhite: '#FFFAF0',snow: '#FFFAFA',yellow: '#FFFF00',lightyellow: '#FFFFE0',ivory: '#FFFFF0',white: '#FFFFFF'};
  48. if (typeof color === 'string') {
  49. return htmlColors[color];
  50. }
  51. }
  52. /**
  53. * Set the color of the colorPicker
  54. * Supported formats:
  55. * 'red' --> HTML color string
  56. * '#ffffff' --> hex string
  57. * 'rbg(255,255,255)' --> rgb string
  58. * 'rgba(255,255,255,1.0)' --> rgba string
  59. * {r:255,g:255,b:255} --> rgb object
  60. * {r:255,g:255,b:255,a:1.0} --> rgba object
  61. * @param color
  62. * @param setInitial
  63. */
  64. setColor(color, setInitial = true) {
  65. if (color === 'none') {
  66. return;
  67. }
  68. let rgba;
  69. // if a html color shorthand is used, convert to hex
  70. var htmlColor = this._isColorString(color);
  71. if (htmlColor !== undefined) {
  72. color = htmlColor;
  73. }
  74. // check format
  75. if (util.isString(color) === true) {
  76. if (util.isValidRGB(color) === true) {
  77. let rgbaArray = color.substr(4).substr(0, color.length - 5).split(',');
  78. rgba = {r:rgbaArray[0], g:rgbaArray[1], b:rgbaArray[2], a:1.0};
  79. }
  80. else if (util.isValidRGBA(color) === true) {
  81. let rgbaArray = color.substr(5).substr(0, color.length - 6).split(',');
  82. rgba = {r:rgbaArray[0], g:rgbaArray[1], b:rgbaArray[2], a:rgbaArray[3]};
  83. }
  84. else if (util.isValidHex(color) === true) {
  85. let rgbObj = util.hexToRGB(color);
  86. rgba = {r:rgbObj.r, g:rgbObj.g, b:rgbObj.b, a:1.0};
  87. }
  88. }
  89. else {
  90. if (color instanceof Object) {
  91. if (color.r !== undefined && color.g !== undefined && color.b !== undefined) {
  92. let alpha = color.a !== undefined ? color.a : '1.0';
  93. rgba = {r:color.r, g:color.g, b:color.b, a:alpha};
  94. }
  95. }
  96. }
  97. // set color
  98. if (rgba === undefined) {
  99. throw new Error("Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: " + JSON.stringify(color));
  100. }
  101. else {
  102. this._setColor(rgba, setInitial);
  103. }
  104. }
  105. /**
  106. * this shows the color picker at a location. The hue circle is constructed once and stored.
  107. * @param x
  108. * @param y
  109. */
  110. show(x,y) {
  111. this.applied = false;
  112. this.frame.style.display = 'block';
  113. this.frame.style.top = y + 'px';
  114. this.frame.style.left = x + 'px';
  115. this._generateHueCircle();
  116. }
  117. // ------------------------------------------ PRIVATE ----------------------------- //
  118. /**
  119. * Hide the picker. Is called by the cancel button.
  120. * Optional boolean to store the previous color for easy access later on.
  121. * @param storePrevious
  122. * @private
  123. */
  124. _hide(storePrevious = true) {
  125. // store the previous color for next time;
  126. if (storePrevious === true) {
  127. this.previousColor = util.extend({}, this.color);
  128. }
  129. if (this.applied === true) {
  130. this.updateCallback(this.initialColor);
  131. }
  132. this.frame.style.display = 'none';
  133. }
  134. /**
  135. * bound to the save button. Saves and hides.
  136. * @private
  137. */
  138. _save() {
  139. this.updateCallback(this.color);
  140. this.applied = false;
  141. this._hide();
  142. }
  143. /**
  144. * Bound to apply button. Saves but does not close. Is undone by the cancel button.
  145. * @private
  146. */
  147. _apply() {
  148. this.applied = true;
  149. this.updateCallback(this.color);
  150. this._updatePicker(this.color);
  151. }
  152. /**
  153. * load the color from the previous session.
  154. * @private
  155. */
  156. _loadLast() {
  157. if (this.previousColor !== undefined) {
  158. this.setColor(this.previousColor, false);
  159. }
  160. else {
  161. alert("There is no last color to load...");
  162. }
  163. }
  164. /**
  165. * set the color, place the picker
  166. * @param rgba
  167. * @param setInitial
  168. * @private
  169. */
  170. _setColor(rgba, setInitial = true) {
  171. // store the initial color
  172. if (setInitial === true) {
  173. this.initialColor = util.extend({}, rgba);
  174. }
  175. this.color = rgba;
  176. let hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b);
  177. let angleConvert = 2 * Math.PI;
  178. let radius = this.r * hsv.s;
  179. let x = this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h);
  180. let y = this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h);
  181. this.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + 'px';
  182. this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + 'px';
  183. this._updatePicker(rgba);
  184. }
  185. /**
  186. * bound to opacity control
  187. * @param value
  188. * @private
  189. */
  190. _setOpacity(value) {
  191. this.color.a = value / 100;
  192. this._updatePicker(this.color);
  193. }
  194. /**
  195. * bound to brightness control
  196. * @param value
  197. * @private
  198. */
  199. _setBrightness(value) {
  200. let hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b);
  201. hsv.v = value / 100;
  202. let rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v);
  203. rgba['a'] = this.color.a;
  204. this.color = rgba;
  205. this._updatePicker();
  206. }
  207. /**
  208. * update the colorpicker. A black circle overlays the hue circle to mimic the brightness decreasing.
  209. * @param rgba
  210. * @private
  211. */
  212. _updatePicker(rgba = this.color) {
  213. let hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b);
  214. let ctx = this.colorPickerCanvas.getContext('2d');
  215. if (this.pixelRation === undefined) {
  216. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  217. ctx.mozBackingStorePixelRatio ||
  218. ctx.msBackingStorePixelRatio ||
  219. ctx.oBackingStorePixelRatio ||
  220. ctx.backingStorePixelRatio || 1);
  221. }
  222. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  223. // clear the canvas
  224. let w = this.colorPickerCanvas.clientWidth;
  225. let h = this.colorPickerCanvas.clientHeight;
  226. ctx.clearRect(0, 0, w, h);
  227. ctx.putImageData(this.hueCircle, 0,0);
  228. ctx.fillStyle = 'rgba(0,0,0,' + (1- hsv.v) + ')';
  229. ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
  230. ctx.fill();
  231. this.brightnessRange.value = 100 * hsv.v;
  232. this.opacityRange.value = 100 * rgba.a;
  233. this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')';
  234. this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')';
  235. }
  236. /**
  237. * used by create to set the size of the canvas.
  238. * @private
  239. */
  240. _setSize() {
  241. this.colorPickerCanvas.style.width = '100%';
  242. this.colorPickerCanvas.style.height = '100%';
  243. this.colorPickerCanvas.width = 289 * this.pixelRatio;
  244. this.colorPickerCanvas.height = 289 * this.pixelRatio;
  245. }
  246. /**
  247. * create all dom elements
  248. * TODO: cleanup, lots of similar dom elements
  249. * @private
  250. */
  251. _create() {
  252. this.frame = document.createElement('div');
  253. this.frame.className = 'vis-color-picker';
  254. this.colorPickerDiv = document.createElement('div');
  255. this.colorPickerSelector = document.createElement('div');
  256. this.colorPickerSelector.className = 'vis-selector';
  257. this.colorPickerDiv.appendChild(this.colorPickerSelector);
  258. this.colorPickerCanvas = document.createElement('canvas');
  259. this.colorPickerDiv.appendChild(this.colorPickerCanvas);
  260. if (!this.colorPickerCanvas.getContext) {
  261. let noCanvas = document.createElement( 'DIV' );
  262. noCanvas.style.color = 'red';
  263. noCanvas.style.fontWeight = 'bold' ;
  264. noCanvas.style.padding = '10px';
  265. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  266. this.colorPickerCanvas.appendChild(noCanvas);
  267. }
  268. else {
  269. let ctx = this.colorPickerCanvas.getContext("2d");
  270. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  271. ctx.mozBackingStorePixelRatio ||
  272. ctx.msBackingStorePixelRatio ||
  273. ctx.oBackingStorePixelRatio ||
  274. ctx.backingStorePixelRatio || 1);
  275. this.colorPickerCanvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  276. }
  277. this.colorPickerDiv.className = 'vis-color';
  278. this.opacityDiv = document.createElement('div');
  279. this.opacityDiv.className = 'vis-opacity';
  280. this.brightnessDiv = document.createElement('div');
  281. this.brightnessDiv.className = 'vis-brightness';
  282. this.arrowDiv = document.createElement('div');
  283. this.arrowDiv.className = 'vis-arrow';
  284. this.opacityRange = document.createElement('input');
  285. try {
  286. this.opacityRange.type = 'range'; // Not supported on IE9
  287. this.opacityRange.min = '0';
  288. this.opacityRange.max = '100';
  289. }
  290. catch (err) {}
  291. this.opacityRange.value = '100';
  292. this.opacityRange.className = 'vis-range';
  293. this.brightnessRange = document.createElement('input');
  294. try {
  295. this.brightnessRange.type = 'range'; // Not supported on IE9
  296. this.brightnessRange.min = '0';
  297. this.brightnessRange.max = '100';
  298. }
  299. catch (err) {}
  300. this.brightnessRange.value = '100';
  301. this.brightnessRange.className = 'vis-range';
  302. this.opacityDiv.appendChild(this.opacityRange);
  303. this.brightnessDiv.appendChild(this.brightnessRange);
  304. var me = this;
  305. this.opacityRange.onchange = function () {me._setOpacity(this.value);};
  306. this.opacityRange.oninput = function () {me._setOpacity(this.value);};
  307. this.brightnessRange.onchange = function () {me._setBrightness(this.value);};
  308. this.brightnessRange.oninput = function () {me._setBrightness(this.value);};
  309. this.brightnessLabel = document.createElement("div");
  310. this.brightnessLabel.className = "vis-label vis-brightness";
  311. this.brightnessLabel.innerHTML = 'brightness:';
  312. this.opacityLabel = document.createElement("div");
  313. this.opacityLabel.className = "vis-label vis-opacity";
  314. this.opacityLabel.innerHTML = 'opacity:';
  315. this.newColorDiv = document.createElement("div");
  316. this.newColorDiv.className = "vis-new-color";
  317. this.newColorDiv.innerHTML = 'new';
  318. this.initialColorDiv = document.createElement("div");
  319. this.initialColorDiv.className = "vis-initial-color";
  320. this.initialColorDiv.innerHTML = 'initial';
  321. this.cancelButton = document.createElement("div");
  322. this.cancelButton.className = "vis-button vis-cancel";
  323. this.cancelButton.innerHTML = 'cancel';
  324. this.cancelButton.onclick = this._hide.bind(this, false);
  325. this.applyButton = document.createElement("div");
  326. this.applyButton.className = "vis-button vis-apply";
  327. this.applyButton.innerHTML = 'apply';
  328. this.applyButton.onclick = this._apply.bind(this);
  329. this.saveButton = document.createElement("div");
  330. this.saveButton.className = "vis-button vis-save";
  331. this.saveButton.innerHTML = 'save';
  332. this.saveButton.onclick = this._save.bind(this);
  333. this.loadButton = document.createElement("div");
  334. this.loadButton.className = "vis-button vis-load";
  335. this.loadButton.innerHTML = 'load last';
  336. this.loadButton.onclick = this._loadLast.bind(this);
  337. this.frame.appendChild(this.colorPickerDiv);
  338. this.frame.appendChild(this.arrowDiv);
  339. this.frame.appendChild(this.brightnessLabel);
  340. this.frame.appendChild(this.brightnessDiv);
  341. this.frame.appendChild(this.opacityLabel);
  342. this.frame.appendChild(this.opacityDiv);
  343. this.frame.appendChild(this.newColorDiv);
  344. this.frame.appendChild(this.initialColorDiv);
  345. this.frame.appendChild(this.cancelButton);
  346. this.frame.appendChild(this.applyButton);
  347. this.frame.appendChild(this.saveButton);
  348. this.frame.appendChild(this.loadButton);
  349. }
  350. /**
  351. * bind hammer to the color picker
  352. * @private
  353. */
  354. _bindHammer() {
  355. this.drag = {};
  356. this.pinch = {};
  357. this.hammer = new Hammer(this.colorPickerCanvas);
  358. this.hammer.get('pinch').set({enable: true});
  359. hammerUtil.onTouch(this.hammer, (event) => {this._moveSelector(event)});
  360. this.hammer.on('tap', (event) => {this._moveSelector(event)});
  361. this.hammer.on('panstart', (event) => {this._moveSelector(event)});
  362. this.hammer.on('panmove', (event) => {this._moveSelector(event)});
  363. this.hammer.on('panend', (event) => {this._moveSelector(event)});
  364. }
  365. /**
  366. * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown.
  367. * @private
  368. */
  369. _generateHueCircle() {
  370. if (this.generated === false) {
  371. let ctx = this.colorPickerCanvas.getContext('2d');
  372. if (this.pixelRation === undefined) {
  373. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  374. ctx.mozBackingStorePixelRatio ||
  375. ctx.msBackingStorePixelRatio ||
  376. ctx.oBackingStorePixelRatio ||
  377. ctx.backingStorePixelRatio || 1);
  378. }
  379. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  380. // clear the canvas
  381. let w = this.colorPickerCanvas.clientWidth;
  382. let h = this.colorPickerCanvas.clientHeight;
  383. ctx.clearRect(0, 0, w, h);
  384. // draw hue circle
  385. let x, y, hue, sat;
  386. this.centerCoordinates = {x: w * 0.5, y: h * 0.5};
  387. this.r = 0.49 * w;
  388. let angleConvert = (2 * Math.PI) / 360;
  389. let hfac = 1 / 360;
  390. let sfac = 1 / this.r;
  391. let rgb;
  392. for (hue = 0; hue < 360; hue++) {
  393. for (sat = 0; sat < this.r; sat++) {
  394. x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue);
  395. y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue);
  396. rgb = util.HSVToRGB(hue * hfac, sat * sfac, 1);
  397. ctx.fillStyle = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
  398. ctx.fillRect(x - 0.5, y - 0.5, 2, 2);
  399. }
  400. }
  401. ctx.strokeStyle = 'rgba(0,0,0,1)';
  402. ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
  403. ctx.stroke();
  404. this.hueCircle = ctx.getImageData(0,0,w,h);
  405. }
  406. this.generated = true;
  407. }
  408. /**
  409. * move the selector. This is called by hammer functions.
  410. *
  411. * @param event
  412. * @private
  413. */
  414. _moveSelector(event) {
  415. let rect = this.colorPickerDiv.getBoundingClientRect();
  416. let left = event.center.x - rect.left;
  417. let top = event.center.y - rect.top;
  418. let centerY = 0.5 * this.colorPickerDiv.clientHeight;
  419. let centerX = 0.5 * this.colorPickerDiv.clientWidth;
  420. let x = left - centerX;
  421. let y = top - centerY;
  422. let angle = Math.atan2(x,y);
  423. let radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX);
  424. let newTop = Math.cos(angle) * radius + centerY;
  425. let newLeft = Math.sin(angle) * radius + centerX;
  426. this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px';
  427. this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px';
  428. // set color
  429. let h = angle / (2 * Math.PI);
  430. h = h < 0 ? h + 1 : h;
  431. let s = radius / this.r;
  432. let hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b);
  433. hsv.h = h;
  434. hsv.s = s;
  435. let rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v);
  436. rgba['a'] = this.color.a;
  437. this.color = rgba;
  438. // update previews
  439. this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')';
  440. this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')';
  441. }
  442. }
  443. export default ColorPicker;