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.

527 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.
  107. * The hue circle is constructed once and stored.
  108. */
  109. show() {
  110. this.applied = false;
  111. this.frame.style.display = 'block';
  112. this._generateHueCircle();
  113. }
  114. // ------------------------------------------ PRIVATE ----------------------------- //
  115. /**
  116. * Hide the picker. Is called by the cancel button.
  117. * Optional boolean to store the previous color for easy access later on.
  118. * @param storePrevious
  119. * @private
  120. */
  121. _hide(storePrevious = true) {
  122. // store the previous color for next time;
  123. if (storePrevious === true) {
  124. this.previousColor = util.extend({}, this.color);
  125. }
  126. if (this.applied === true) {
  127. this.updateCallback(this.initialColor);
  128. }
  129. this.frame.style.display = 'none';
  130. }
  131. /**
  132. * bound to the save button. Saves and hides.
  133. * @private
  134. */
  135. _save() {
  136. this.updateCallback(this.color);
  137. this.applied = false;
  138. this._hide();
  139. }
  140. /**
  141. * Bound to apply button. Saves but does not close. Is undone by the cancel button.
  142. * @private
  143. */
  144. _apply() {
  145. this.applied = true;
  146. this.updateCallback(this.color);
  147. this._updatePicker(this.color);
  148. }
  149. /**
  150. * load the color from the previous session.
  151. * @private
  152. */
  153. _loadLast() {
  154. if (this.previousColor !== undefined) {
  155. this.setColor(this.previousColor, false);
  156. }
  157. else {
  158. alert("There is no last color to load...");
  159. }
  160. }
  161. /**
  162. * set the color, place the picker
  163. * @param rgba
  164. * @param setInitial
  165. * @private
  166. */
  167. _setColor(rgba, setInitial = true) {
  168. // store the initial color
  169. if (setInitial === true) {
  170. this.initialColor = util.extend({}, rgba);
  171. }
  172. this.color = rgba;
  173. let hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b);
  174. let angleConvert = 2 * Math.PI;
  175. let radius = this.r * hsv.s;
  176. let x = this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h);
  177. let y = this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h);
  178. this.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + 'px';
  179. this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + 'px';
  180. this._updatePicker(rgba);
  181. }
  182. /**
  183. * bound to opacity control
  184. * @param value
  185. * @private
  186. */
  187. _setOpacity(value) {
  188. this.color.a = value / 100;
  189. this._updatePicker(this.color);
  190. }
  191. /**
  192. * bound to brightness control
  193. * @param value
  194. * @private
  195. */
  196. _setBrightness(value) {
  197. let hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b);
  198. hsv.v = value / 100;
  199. let rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v);
  200. rgba['a'] = this.color.a;
  201. this.color = rgba;
  202. this._updatePicker();
  203. }
  204. /**
  205. * update the colorpicker. A black circle overlays the hue circle to mimic the brightness decreasing.
  206. * @param rgba
  207. * @private
  208. */
  209. _updatePicker(rgba = this.color) {
  210. let hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b);
  211. let ctx = this.colorPickerCanvas.getContext('2d');
  212. if (this.pixelRation === undefined) {
  213. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  214. ctx.mozBackingStorePixelRatio ||
  215. ctx.msBackingStorePixelRatio ||
  216. ctx.oBackingStorePixelRatio ||
  217. ctx.backingStorePixelRatio || 1);
  218. }
  219. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  220. // clear the canvas
  221. let w = this.colorPickerCanvas.clientWidth;
  222. let h = this.colorPickerCanvas.clientHeight;
  223. ctx.clearRect(0, 0, w, h);
  224. ctx.putImageData(this.hueCircle, 0,0);
  225. ctx.fillStyle = 'rgba(0,0,0,' + (1- hsv.v) + ')';
  226. ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
  227. ctx.fill();
  228. this.brightnessRange.value = 100 * hsv.v;
  229. this.opacityRange.value = 100 * rgba.a;
  230. this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')';
  231. this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')';
  232. }
  233. /**
  234. * used by create to set the size of the canvas.
  235. * @private
  236. */
  237. _setSize() {
  238. this.colorPickerCanvas.style.width = '100%';
  239. this.colorPickerCanvas.style.height = '100%';
  240. this.colorPickerCanvas.width = 289 * this.pixelRatio;
  241. this.colorPickerCanvas.height = 289 * this.pixelRatio;
  242. }
  243. /**
  244. * create all dom elements
  245. * TODO: cleanup, lots of similar dom elements
  246. * @private
  247. */
  248. _create() {
  249. this.frame = document.createElement('div');
  250. this.frame.className = 'vis-color-picker';
  251. this.colorPickerDiv = document.createElement('div');
  252. this.colorPickerSelector = document.createElement('div');
  253. this.colorPickerSelector.className = 'vis-selector';
  254. this.colorPickerDiv.appendChild(this.colorPickerSelector);
  255. this.colorPickerCanvas = document.createElement('canvas');
  256. this.colorPickerDiv.appendChild(this.colorPickerCanvas);
  257. if (!this.colorPickerCanvas.getContext) {
  258. let noCanvas = document.createElement( 'DIV' );
  259. noCanvas.style.color = 'red';
  260. noCanvas.style.fontWeight = 'bold' ;
  261. noCanvas.style.padding = '10px';
  262. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  263. this.colorPickerCanvas.appendChild(noCanvas);
  264. }
  265. else {
  266. let ctx = this.colorPickerCanvas.getContext("2d");
  267. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  268. ctx.mozBackingStorePixelRatio ||
  269. ctx.msBackingStorePixelRatio ||
  270. ctx.oBackingStorePixelRatio ||
  271. ctx.backingStorePixelRatio || 1);
  272. this.colorPickerCanvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  273. }
  274. this.colorPickerDiv.className = 'vis-color';
  275. this.opacityDiv = document.createElement('div');
  276. this.opacityDiv.className = 'vis-opacity';
  277. this.brightnessDiv = document.createElement('div');
  278. this.brightnessDiv.className = 'vis-brightness';
  279. this.arrowDiv = document.createElement('div');
  280. this.arrowDiv.className = 'vis-arrow';
  281. this.opacityRange = document.createElement('input');
  282. try {
  283. this.opacityRange.type = 'range'; // Not supported on IE9
  284. this.opacityRange.min = '0';
  285. this.opacityRange.max = '100';
  286. }
  287. catch (err) {}
  288. this.opacityRange.value = '100';
  289. this.opacityRange.className = 'vis-range';
  290. this.brightnessRange = document.createElement('input');
  291. try {
  292. this.brightnessRange.type = 'range'; // Not supported on IE9
  293. this.brightnessRange.min = '0';
  294. this.brightnessRange.max = '100';
  295. }
  296. catch (err) {}
  297. this.brightnessRange.value = '100';
  298. this.brightnessRange.className = 'vis-range';
  299. this.opacityDiv.appendChild(this.opacityRange);
  300. this.brightnessDiv.appendChild(this.brightnessRange);
  301. var me = this;
  302. this.opacityRange.onchange = function () {me._setOpacity(this.value);};
  303. this.opacityRange.oninput = function () {me._setOpacity(this.value);};
  304. this.brightnessRange.onchange = function () {me._setBrightness(this.value);};
  305. this.brightnessRange.oninput = function () {me._setBrightness(this.value);};
  306. this.brightnessLabel = document.createElement("div");
  307. this.brightnessLabel.className = "vis-label vis-brightness";
  308. this.brightnessLabel.innerHTML = 'brightness:';
  309. this.opacityLabel = document.createElement("div");
  310. this.opacityLabel.className = "vis-label vis-opacity";
  311. this.opacityLabel.innerHTML = 'opacity:';
  312. this.newColorDiv = document.createElement("div");
  313. this.newColorDiv.className = "vis-new-color";
  314. this.newColorDiv.innerHTML = 'new';
  315. this.initialColorDiv = document.createElement("div");
  316. this.initialColorDiv.className = "vis-initial-color";
  317. this.initialColorDiv.innerHTML = 'initial';
  318. this.cancelButton = document.createElement("div");
  319. this.cancelButton.className = "vis-button vis-cancel";
  320. this.cancelButton.innerHTML = 'cancel';
  321. this.cancelButton.onclick = this._hide.bind(this, false);
  322. this.applyButton = document.createElement("div");
  323. this.applyButton.className = "vis-button vis-apply";
  324. this.applyButton.innerHTML = 'apply';
  325. this.applyButton.onclick = this._apply.bind(this);
  326. this.saveButton = document.createElement("div");
  327. this.saveButton.className = "vis-button vis-save";
  328. this.saveButton.innerHTML = 'save';
  329. this.saveButton.onclick = this._save.bind(this);
  330. this.loadButton = document.createElement("div");
  331. this.loadButton.className = "vis-button vis-load";
  332. this.loadButton.innerHTML = 'load last';
  333. this.loadButton.onclick = this._loadLast.bind(this);
  334. this.frame.appendChild(this.colorPickerDiv);
  335. this.frame.appendChild(this.arrowDiv);
  336. this.frame.appendChild(this.brightnessLabel);
  337. this.frame.appendChild(this.brightnessDiv);
  338. this.frame.appendChild(this.opacityLabel);
  339. this.frame.appendChild(this.opacityDiv);
  340. this.frame.appendChild(this.newColorDiv);
  341. this.frame.appendChild(this.initialColorDiv);
  342. this.frame.appendChild(this.cancelButton);
  343. this.frame.appendChild(this.applyButton);
  344. this.frame.appendChild(this.saveButton);
  345. this.frame.appendChild(this.loadButton);
  346. }
  347. /**
  348. * bind hammer to the color picker
  349. * @private
  350. */
  351. _bindHammer() {
  352. this.drag = {};
  353. this.pinch = {};
  354. this.hammer = new Hammer(this.colorPickerCanvas);
  355. this.hammer.get('pinch').set({enable: true});
  356. hammerUtil.onTouch(this.hammer, (event) => {this._moveSelector(event)});
  357. this.hammer.on('tap', (event) => {this._moveSelector(event)});
  358. this.hammer.on('panstart', (event) => {this._moveSelector(event)});
  359. this.hammer.on('panmove', (event) => {this._moveSelector(event)});
  360. this.hammer.on('panend', (event) => {this._moveSelector(event)});
  361. }
  362. /**
  363. * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown.
  364. * @private
  365. */
  366. _generateHueCircle() {
  367. if (this.generated === false) {
  368. let ctx = this.colorPickerCanvas.getContext('2d');
  369. if (this.pixelRation === undefined) {
  370. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  371. ctx.mozBackingStorePixelRatio ||
  372. ctx.msBackingStorePixelRatio ||
  373. ctx.oBackingStorePixelRatio ||
  374. ctx.backingStorePixelRatio || 1);
  375. }
  376. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  377. // clear the canvas
  378. let w = this.colorPickerCanvas.clientWidth;
  379. let h = this.colorPickerCanvas.clientHeight;
  380. ctx.clearRect(0, 0, w, h);
  381. // draw hue circle
  382. let x, y, hue, sat;
  383. this.centerCoordinates = {x: w * 0.5, y: h * 0.5};
  384. this.r = 0.49 * w;
  385. let angleConvert = (2 * Math.PI) / 360;
  386. let hfac = 1 / 360;
  387. let sfac = 1 / this.r;
  388. let rgb;
  389. for (hue = 0; hue < 360; hue++) {
  390. for (sat = 0; sat < this.r; sat++) {
  391. x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue);
  392. y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue);
  393. rgb = util.HSVToRGB(hue * hfac, sat * sfac, 1);
  394. ctx.fillStyle = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
  395. ctx.fillRect(x - 0.5, y - 0.5, 2, 2);
  396. }
  397. }
  398. ctx.strokeStyle = 'rgba(0,0,0,1)';
  399. ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
  400. ctx.stroke();
  401. this.hueCircle = ctx.getImageData(0,0,w,h);
  402. }
  403. this.generated = true;
  404. }
  405. /**
  406. * move the selector. This is called by hammer functions.
  407. *
  408. * @param event
  409. * @private
  410. */
  411. _moveSelector(event) {
  412. let rect = this.colorPickerDiv.getBoundingClientRect();
  413. let left = event.center.x - rect.left;
  414. let top = event.center.y - rect.top;
  415. let centerY = 0.5 * this.colorPickerDiv.clientHeight;
  416. let centerX = 0.5 * this.colorPickerDiv.clientWidth;
  417. let x = left - centerX;
  418. let y = top - centerY;
  419. let angle = Math.atan2(x,y);
  420. let radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX);
  421. let newTop = Math.cos(angle) * radius + centerY;
  422. let newLeft = Math.sin(angle) * radius + centerX;
  423. this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px';
  424. this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px';
  425. // set color
  426. let h = angle / (2 * Math.PI);
  427. h = h < 0 ? h + 1 : h;
  428. let s = radius / this.r;
  429. let hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b);
  430. hsv.h = h;
  431. hsv.s = s;
  432. let rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v);
  433. rgba['a'] = this.color.a;
  434. this.color = rgba;
  435. // update previews
  436. this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')';
  437. this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')';
  438. }
  439. }
  440. export default ColorPicker;