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.

525 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. this.opacityRange.type = 'range';
  286. this.opacityRange.min = '0';
  287. this.opacityRange.max = '100';
  288. this.opacityRange.value = '100';
  289. this.opacityRange.className = 'vis-range';
  290. this.brightnessRange = document.createElement('input');
  291. this.brightnessRange.type = 'range';
  292. this.brightnessRange.min = '0';
  293. this.brightnessRange.max = '100';
  294. this.brightnessRange.value = '100';
  295. this.brightnessRange.className = 'vis-range';
  296. this.opacityDiv.appendChild(this.opacityRange);
  297. this.brightnessDiv.appendChild(this.brightnessRange);
  298. var me = this;
  299. this.opacityRange.onchange = function () {me._setOpacity(this.value);};
  300. this.opacityRange.oninput = function () {me._setOpacity(this.value);};
  301. this.brightnessRange.onchange = function () {me._setBrightness(this.value);};
  302. this.brightnessRange.oninput = function () {me._setBrightness(this.value);};
  303. this.brightnessLabel = document.createElement("div");
  304. this.brightnessLabel.className = "vis-label vis-brightness";
  305. this.brightnessLabel.innerHTML = 'brightness:';
  306. this.opacityLabel = document.createElement("div");
  307. this.opacityLabel.className = "vis-label vis-opacity";
  308. this.opacityLabel.innerHTML = 'opacity:';
  309. this.newColorDiv = document.createElement("div");
  310. this.newColorDiv.className = "vis-new-color";
  311. this.newColorDiv.innerHTML = 'new';
  312. this.initialColorDiv = document.createElement("div");
  313. this.initialColorDiv.className = "vis-initial-color";
  314. this.initialColorDiv.innerHTML = 'initial';
  315. this.cancelButton = document.createElement("div");
  316. this.cancelButton.className = "vis-button vis-cancel";
  317. this.cancelButton.innerHTML = 'cancel';
  318. this.cancelButton.onclick = this._hide.bind(this, false);
  319. this.applyButton = document.createElement("div");
  320. this.applyButton.className = "vis-button vis-apply";
  321. this.applyButton.innerHTML = 'apply';
  322. this.applyButton.onclick = this._apply.bind(this);
  323. this.saveButton = document.createElement("div");
  324. this.saveButton.className = "vis-button vis-save";
  325. this.saveButton.innerHTML = 'save';
  326. this.saveButton.onclick = this._save.bind(this);
  327. this.loadButton = document.createElement("div");
  328. this.loadButton.className = "vis-button vis-load";
  329. this.loadButton.innerHTML = 'load last';
  330. this.loadButton.onclick = this._loadLast.bind(this);
  331. this.frame.appendChild(this.colorPickerDiv);
  332. this.frame.appendChild(this.arrowDiv);
  333. this.frame.appendChild(this.brightnessLabel);
  334. this.frame.appendChild(this.brightnessDiv);
  335. this.frame.appendChild(this.opacityLabel);
  336. this.frame.appendChild(this.opacityDiv);
  337. this.frame.appendChild(this.newColorDiv);
  338. this.frame.appendChild(this.initialColorDiv);
  339. this.frame.appendChild(this.cancelButton);
  340. this.frame.appendChild(this.applyButton);
  341. this.frame.appendChild(this.saveButton);
  342. this.frame.appendChild(this.loadButton);
  343. }
  344. /**
  345. * bind hammer to the color picker
  346. * @private
  347. */
  348. _bindHammer() {
  349. this.drag = {};
  350. this.pinch = {};
  351. this.hammer = new Hammer(this.colorPickerCanvas);
  352. this.hammer.get('pinch').set({enable: true});
  353. hammerUtil.onTouch(this.hammer, (event) => {this._moveSelector(event)});
  354. this.hammer.on('tap', (event) => {this._moveSelector(event)});
  355. this.hammer.on('panstart', (event) => {this._moveSelector(event)});
  356. this.hammer.on('panmove', (event) => {this._moveSelector(event)});
  357. this.hammer.on('panend', (event) => {this._moveSelector(event)});
  358. }
  359. /**
  360. * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown.
  361. * @private
  362. */
  363. _generateHueCircle() {
  364. if (this.generated === false) {
  365. let ctx = this.colorPickerCanvas.getContext('2d');
  366. if (this.pixelRation === undefined) {
  367. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  368. ctx.mozBackingStorePixelRatio ||
  369. ctx.msBackingStorePixelRatio ||
  370. ctx.oBackingStorePixelRatio ||
  371. ctx.backingStorePixelRatio || 1);
  372. }
  373. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  374. // clear the canvas
  375. let w = this.colorPickerCanvas.clientWidth;
  376. let h = this.colorPickerCanvas.clientHeight;
  377. ctx.clearRect(0, 0, w, h);
  378. // draw hue circle
  379. let x, y, hue, sat;
  380. this.centerCoordinates = {x: w * 0.5, y: h * 0.5};
  381. this.r = 0.49 * w;
  382. let angleConvert = (2 * Math.PI) / 360;
  383. let hfac = 1 / 360;
  384. let sfac = 1 / this.r;
  385. let rgb;
  386. for (hue = 0; hue < 360; hue++) {
  387. for (sat = 0; sat < this.r; sat++) {
  388. x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue);
  389. y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue);
  390. rgb = util.HSVToRGB(hue * hfac, sat * sfac, 1);
  391. ctx.fillStyle = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
  392. ctx.fillRect(x - 0.5, y - 0.5, 2, 2);
  393. }
  394. }
  395. ctx.strokeStyle = 'rgba(0,0,0,1)';
  396. ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
  397. ctx.stroke();
  398. this.hueCircle = ctx.getImageData(0,0,w,h);
  399. }
  400. this.generated = true;
  401. }
  402. /**
  403. * move the selector. This is called by hammer functions.
  404. *
  405. * @param event
  406. * @private
  407. */
  408. _moveSelector(event) {
  409. let rect = this.colorPickerDiv.getBoundingClientRect();
  410. let left = event.center.x - rect.left;
  411. let top = event.center.y - rect.top;
  412. let centerY = 0.5 * this.colorPickerDiv.clientHeight;
  413. let centerX = 0.5 * this.colorPickerDiv.clientWidth;
  414. let x = left - centerX;
  415. let y = top - centerY;
  416. let angle = Math.atan2(x,y);
  417. let radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX);
  418. let newTop = Math.cos(angle) * radius + centerY;
  419. let newLeft = Math.sin(angle) * radius + centerX;
  420. this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px';
  421. this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px';
  422. // set color
  423. let h = angle / (2 * Math.PI);
  424. h = h < 0 ? h + 1 : h;
  425. let s = radius / this.r;
  426. let hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b);
  427. hsv.h = h;
  428. hsv.s = s;
  429. let rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v);
  430. rgba['a'] = this.color.a;
  431. this.color = rgba;
  432. // update previews
  433. this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')';
  434. this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')';
  435. }
  436. }
  437. export default ColorPicker;