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.

2278 lines
70 KiB

  1. var Emitter = require('emitter-component');
  2. var DataSet = require('../DataSet');
  3. var DataView = require('../DataView');
  4. var util = require('../util');
  5. var Point3d = require('./Point3d');
  6. var Point2d = require('./Point2d');
  7. var Camera = require('./Camera');
  8. var Filter = require('./Filter');
  9. var Slider = require('./Slider');
  10. var StepNumber = require('./StepNumber');
  11. /**
  12. * @constructor Graph3d
  13. * Graph3d displays data in 3d.
  14. *
  15. * Graph3d is developed in javascript as a Google Visualization Chart.
  16. *
  17. * @param {Element} container The DOM element in which the Graph3d will
  18. * be created. Normally a div element.
  19. * @param {DataSet | DataView | Array} [data]
  20. * @param {Object} [options]
  21. */
  22. function Graph3d(container, data, options) {
  23. if (!(this instanceof Graph3d)) {
  24. throw new SyntaxError('Constructor must be called with the new operator');
  25. }
  26. // create variables and set default values
  27. this.containerElement = container;
  28. this.width = '400px';
  29. this.height = '400px';
  30. this.margin = 10; // px
  31. this.defaultXCenter = '55%';
  32. this.defaultYCenter = '50%';
  33. this.xLabel = 'x';
  34. this.yLabel = 'y';
  35. this.zLabel = 'z';
  36. var passValueFn = function(v) { return v; };
  37. this.xValueLabel = passValueFn;
  38. this.yValueLabel = passValueFn;
  39. this.zValueLabel = passValueFn;
  40. this.filterLabel = 'time';
  41. this.legendLabel = 'value';
  42. this.style = Graph3d.STYLE.DOT;
  43. this.showPerspective = true;
  44. this.showGrid = true;
  45. this.keepAspectRatio = true;
  46. this.showShadow = false;
  47. this.showGrayBottom = false; // TODO: this does not work correctly
  48. this.showTooltip = false;
  49. this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube'
  50. this.animationInterval = 1000; // milliseconds
  51. this.animationPreload = false;
  52. this.camera = new Camera();
  53. this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
  54. this.dataTable = null; // The original data table
  55. this.dataPoints = null; // The table with point objects
  56. // the column indexes
  57. this.colX = undefined;
  58. this.colY = undefined;
  59. this.colZ = undefined;
  60. this.colValue = undefined;
  61. this.colFilter = undefined;
  62. this.xMin = 0;
  63. this.xStep = undefined; // auto by default
  64. this.xMax = 1;
  65. this.yMin = 0;
  66. this.yStep = undefined; // auto by default
  67. this.yMax = 1;
  68. this.zMin = 0;
  69. this.zStep = undefined; // auto by default
  70. this.zMax = 1;
  71. this.valueMin = 0;
  72. this.valueMax = 1;
  73. this.xBarWidth = 1;
  74. this.yBarWidth = 1;
  75. // TODO: customize axis range
  76. // constants
  77. this.colorAxis = '#4D4D4D';
  78. this.colorGrid = '#D3D3D3';
  79. this.colorDot = '#7DC1FF';
  80. this.colorDotBorder = '#3267D2';
  81. // create a frame and canvas
  82. this.create();
  83. // apply options (also when undefined)
  84. this.setOptions(options);
  85. // apply data
  86. if (data) {
  87. this.setData(data);
  88. }
  89. }
  90. // Extend Graph3d with an Emitter mixin
  91. Emitter(Graph3d.prototype);
  92. /**
  93. * Calculate the scaling values, dependent on the range in x, y, and z direction
  94. */
  95. Graph3d.prototype._setScale = function() {
  96. this.scale = new Point3d(1 / (this.xMax - this.xMin),
  97. 1 / (this.yMax - this.yMin),
  98. 1 / (this.zMax - this.zMin));
  99. // keep aspect ration between x and y scale if desired
  100. if (this.keepAspectRatio) {
  101. if (this.scale.x < this.scale.y) {
  102. //noinspection JSSuspiciousNameCombination
  103. this.scale.y = this.scale.x;
  104. }
  105. else {
  106. //noinspection JSSuspiciousNameCombination
  107. this.scale.x = this.scale.y;
  108. }
  109. }
  110. // scale the vertical axis
  111. this.scale.z *= this.verticalRatio;
  112. // TODO: can this be automated? verticalRatio?
  113. // determine scale for (optional) value
  114. this.scale.value = 1 / (this.valueMax - this.valueMin);
  115. // position the camera arm
  116. var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x;
  117. var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y;
  118. var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z;
  119. this.camera.setArmLocation(xCenter, yCenter, zCenter);
  120. };
  121. /**
  122. * Convert a 3D location to a 2D location on screen
  123. * http://en.wikipedia.org/wiki/3D_projection
  124. * @param {Point3d} point3d A 3D point with parameters x, y, z
  125. * @return {Point2d} point2d A 2D point with parameters x, y
  126. */
  127. Graph3d.prototype._convert3Dto2D = function(point3d) {
  128. var translation = this._convertPointToTranslation(point3d);
  129. return this._convertTranslationToScreen(translation);
  130. };
  131. /**
  132. * Convert a 3D location its translation seen from the camera
  133. * http://en.wikipedia.org/wiki/3D_projection
  134. * @param {Point3d} point3d A 3D point with parameters x, y, z
  135. * @return {Point3d} translation A 3D point with parameters x, y, z This is
  136. * the translation of the point, seen from the
  137. * camera
  138. */
  139. Graph3d.prototype._convertPointToTranslation = function(point3d) {
  140. var ax = point3d.x * this.scale.x,
  141. ay = point3d.y * this.scale.y,
  142. az = point3d.z * this.scale.z,
  143. cx = this.camera.getCameraLocation().x,
  144. cy = this.camera.getCameraLocation().y,
  145. cz = this.camera.getCameraLocation().z,
  146. // calculate angles
  147. sinTx = Math.sin(this.camera.getCameraRotation().x),
  148. cosTx = Math.cos(this.camera.getCameraRotation().x),
  149. sinTy = Math.sin(this.camera.getCameraRotation().y),
  150. cosTy = Math.cos(this.camera.getCameraRotation().y),
  151. sinTz = Math.sin(this.camera.getCameraRotation().z),
  152. cosTz = Math.cos(this.camera.getCameraRotation().z),
  153. // calculate translation
  154. dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
  155. dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)),
  156. dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx));
  157. return new Point3d(dx, dy, dz);
  158. };
  159. /**
  160. * Convert a translation point to a point on the screen
  161. * @param {Point3d} translation A 3D point with parameters x, y, z This is
  162. * the translation of the point, seen from the
  163. * camera
  164. * @return {Point2d} point2d A 2D point with parameters x, y
  165. */
  166. Graph3d.prototype._convertTranslationToScreen = function(translation) {
  167. var ex = this.eye.x,
  168. ey = this.eye.y,
  169. ez = this.eye.z,
  170. dx = translation.x,
  171. dy = translation.y,
  172. dz = translation.z;
  173. // calculate position on screen from translation
  174. var bx;
  175. var by;
  176. if (this.showPerspective) {
  177. bx = (dx - ex) * (ez / dz);
  178. by = (dy - ey) * (ez / dz);
  179. }
  180. else {
  181. bx = dx * -(ez / this.camera.getArmLength());
  182. by = dy * -(ez / this.camera.getArmLength());
  183. }
  184. // shift and scale the point to the center of the screen
  185. // use the width of the graph to scale both horizontally and vertically.
  186. return new Point2d(
  187. this.xcenter + bx * this.frame.canvas.clientWidth,
  188. this.ycenter - by * this.frame.canvas.clientWidth);
  189. };
  190. /**
  191. * Set the background styling for the graph
  192. * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
  193. */
  194. Graph3d.prototype._setBackgroundColor = function(backgroundColor) {
  195. var fill = 'white';
  196. var stroke = 'gray';
  197. var strokeWidth = 1;
  198. if (typeof(backgroundColor) === 'string') {
  199. fill = backgroundColor;
  200. stroke = 'none';
  201. strokeWidth = 0;
  202. }
  203. else if (typeof(backgroundColor) === 'object') {
  204. if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
  205. if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
  206. if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
  207. }
  208. else if (backgroundColor === undefined) {
  209. // use use defaults
  210. }
  211. else {
  212. throw 'Unsupported type of backgroundColor';
  213. }
  214. this.frame.style.backgroundColor = fill;
  215. this.frame.style.borderColor = stroke;
  216. this.frame.style.borderWidth = strokeWidth + 'px';
  217. this.frame.style.borderStyle = 'solid';
  218. };
  219. /// enumerate the available styles
  220. Graph3d.STYLE = {
  221. BAR: 0,
  222. BARCOLOR: 1,
  223. BARSIZE: 2,
  224. DOT : 3,
  225. DOTLINE : 4,
  226. DOTCOLOR: 5,
  227. DOTSIZE: 6,
  228. GRID : 7,
  229. LINE: 8,
  230. SURFACE : 9
  231. };
  232. /**
  233. * Retrieve the style index from given styleName
  234. * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
  235. * @return {Number} styleNumber Enumeration value representing the style, or -1
  236. * when not found
  237. */
  238. Graph3d.prototype._getStyleNumber = function(styleName) {
  239. switch (styleName) {
  240. case 'dot': return Graph3d.STYLE.DOT;
  241. case 'dot-line': return Graph3d.STYLE.DOTLINE;
  242. case 'dot-color': return Graph3d.STYLE.DOTCOLOR;
  243. case 'dot-size': return Graph3d.STYLE.DOTSIZE;
  244. case 'line': return Graph3d.STYLE.LINE;
  245. case 'grid': return Graph3d.STYLE.GRID;
  246. case 'surface': return Graph3d.STYLE.SURFACE;
  247. case 'bar': return Graph3d.STYLE.BAR;
  248. case 'bar-color': return Graph3d.STYLE.BARCOLOR;
  249. case 'bar-size': return Graph3d.STYLE.BARSIZE;
  250. }
  251. return -1;
  252. };
  253. /**
  254. * Determine the indexes of the data columns, based on the given style and data
  255. * @param {DataSet} data
  256. * @param {Number} style
  257. */
  258. Graph3d.prototype._determineColumnIndexes = function(data, style) {
  259. if (this.style === Graph3d.STYLE.DOT ||
  260. this.style === Graph3d.STYLE.DOTLINE ||
  261. this.style === Graph3d.STYLE.LINE ||
  262. this.style === Graph3d.STYLE.GRID ||
  263. this.style === Graph3d.STYLE.SURFACE ||
  264. this.style === Graph3d.STYLE.BAR) {
  265. // 3 columns expected, and optionally a 4th with filter values
  266. this.colX = 0;
  267. this.colY = 1;
  268. this.colZ = 2;
  269. this.colValue = undefined;
  270. if (data.getNumberOfColumns() > 3) {
  271. this.colFilter = 3;
  272. }
  273. }
  274. else if (this.style === Graph3d.STYLE.DOTCOLOR ||
  275. this.style === Graph3d.STYLE.DOTSIZE ||
  276. this.style === Graph3d.STYLE.BARCOLOR ||
  277. this.style === Graph3d.STYLE.BARSIZE) {
  278. // 4 columns expected, and optionally a 5th with filter values
  279. this.colX = 0;
  280. this.colY = 1;
  281. this.colZ = 2;
  282. this.colValue = 3;
  283. if (data.getNumberOfColumns() > 4) {
  284. this.colFilter = 4;
  285. }
  286. }
  287. else {
  288. throw 'Unknown style "' + this.style + '"';
  289. }
  290. };
  291. Graph3d.prototype.getNumberOfRows = function(data) {
  292. return data.length;
  293. }
  294. Graph3d.prototype.getNumberOfColumns = function(data) {
  295. var counter = 0;
  296. for (var column in data[0]) {
  297. if (data[0].hasOwnProperty(column)) {
  298. counter++;
  299. }
  300. }
  301. return counter;
  302. }
  303. Graph3d.prototype.getDistinctValues = function(data, column) {
  304. var distinctValues = [];
  305. for (var i = 0; i < data.length; i++) {
  306. if (distinctValues.indexOf(data[i][column]) == -1) {
  307. distinctValues.push(data[i][column]);
  308. }
  309. }
  310. return distinctValues;
  311. }
  312. Graph3d.prototype.getColumnRange = function(data,column) {
  313. var minMax = {min:data[0][column],max:data[0][column]};
  314. for (var i = 0; i < data.length; i++) {
  315. if (minMax.min > data[i][column]) { minMax.min = data[i][column]; }
  316. if (minMax.max < data[i][column]) { minMax.max = data[i][column]; }
  317. }
  318. return minMax;
  319. };
  320. /**
  321. * Initialize the data from the data table. Calculate minimum and maximum values
  322. * and column index values
  323. * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph.
  324. * @param {Number} style Style Number
  325. */
  326. Graph3d.prototype._dataInitialize = function (rawData, style) {
  327. var me = this;
  328. // unsubscribe from the dataTable
  329. if (this.dataSet) {
  330. this.dataSet.off('*', this._onChange);
  331. }
  332. if (rawData === undefined)
  333. return;
  334. if (Array.isArray(rawData)) {
  335. rawData = new DataSet(rawData);
  336. }
  337. var data;
  338. if (rawData instanceof DataSet || rawData instanceof DataView) {
  339. data = rawData.get();
  340. }
  341. else {
  342. throw new Error('Array, DataSet, or DataView expected');
  343. }
  344. if (data.length == 0)
  345. return;
  346. this.dataSet = rawData;
  347. this.dataTable = data;
  348. // subscribe to changes in the dataset
  349. this._onChange = function () {
  350. me.setData(me.dataSet);
  351. };
  352. this.dataSet.on('*', this._onChange);
  353. // _determineColumnIndexes
  354. // getNumberOfRows (points)
  355. // getNumberOfColumns (x,y,z,v,t,t1,t2...)
  356. // getDistinctValues (unique values?)
  357. // getColumnRange
  358. // determine the location of x,y,z,value,filter columns
  359. this.colX = 'x';
  360. this.colY = 'y';
  361. this.colZ = 'z';
  362. this.colValue = 'style';
  363. this.colFilter = 'filter';
  364. // check if a filter column is provided
  365. if (data[0].hasOwnProperty('filter')) {
  366. if (this.dataFilter === undefined) {
  367. this.dataFilter = new Filter(rawData, this.colFilter, this);
  368. this.dataFilter.setOnLoadCallback(function() {me.redraw();});
  369. }
  370. }
  371. var withBars = this.style == Graph3d.STYLE.BAR ||
  372. this.style == Graph3d.STYLE.BARCOLOR ||
  373. this.style == Graph3d.STYLE.BARSIZE;
  374. // determine barWidth from data
  375. if (withBars) {
  376. if (this.defaultXBarWidth !== undefined) {
  377. this.xBarWidth = this.defaultXBarWidth;
  378. }
  379. else {
  380. var dataX = this.getDistinctValues(data,this.colX);
  381. this.xBarWidth = (dataX[1] - dataX[0]) || 1;
  382. }
  383. if (this.defaultYBarWidth !== undefined) {
  384. this.yBarWidth = this.defaultYBarWidth;
  385. }
  386. else {
  387. var dataY = this.getDistinctValues(data,this.colY);
  388. this.yBarWidth = (dataY[1] - dataY[0]) || 1;
  389. }
  390. }
  391. // calculate minimums and maximums
  392. var xRange = this.getColumnRange(data,this.colX);
  393. if (withBars) {
  394. xRange.min -= this.xBarWidth / 2;
  395. xRange.max += this.xBarWidth / 2;
  396. }
  397. this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min;
  398. this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max;
  399. if (this.xMax <= this.xMin) this.xMax = this.xMin + 1;
  400. this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5;
  401. var yRange = this.getColumnRange(data,this.colY);
  402. if (withBars) {
  403. yRange.min -= this.yBarWidth / 2;
  404. yRange.max += this.yBarWidth / 2;
  405. }
  406. this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min;
  407. this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max;
  408. if (this.yMax <= this.yMin) this.yMax = this.yMin + 1;
  409. this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5;
  410. var zRange = this.getColumnRange(data,this.colZ);
  411. this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min;
  412. this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max;
  413. if (this.zMax <= this.zMin) this.zMax = this.zMin + 1;
  414. this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5;
  415. if (this.colValue !== undefined) {
  416. var valueRange = this.getColumnRange(data,this.colValue);
  417. this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min;
  418. this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max;
  419. if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1;
  420. }
  421. // set the scale dependent on the ranges.
  422. this._setScale();
  423. };
  424. /**
  425. * Filter the data based on the current filter
  426. * @param {Array} data
  427. * @return {Array} dataPoints Array with point objects which can be drawn on screen
  428. */
  429. Graph3d.prototype._getDataPoints = function (data) {
  430. // TODO: store the created matrix dataPoints in the filters instead of reloading each time
  431. var x, y, i, z, obj, point;
  432. var dataPoints = [];
  433. if (this.style === Graph3d.STYLE.GRID ||
  434. this.style === Graph3d.STYLE.SURFACE) {
  435. // copy all values from the google data table to a matrix
  436. // the provided values are supposed to form a grid of (x,y) positions
  437. // create two lists with all present x and y values
  438. var dataX = [];
  439. var dataY = [];
  440. for (i = 0; i < this.getNumberOfRows(data); i++) {
  441. x = data[i][this.colX] || 0;
  442. y = data[i][this.colY] || 0;
  443. if (dataX.indexOf(x) === -1) {
  444. dataX.push(x);
  445. }
  446. if (dataY.indexOf(y) === -1) {
  447. dataY.push(y);
  448. }
  449. }
  450. function sortNumber(a, b) {
  451. return a - b;
  452. }
  453. dataX.sort(sortNumber);
  454. dataY.sort(sortNumber);
  455. // create a grid, a 2d matrix, with all values.
  456. var dataMatrix = []; // temporary data matrix
  457. for (i = 0; i < data.length; i++) {
  458. x = data[i][this.colX] || 0;
  459. y = data[i][this.colY] || 0;
  460. z = data[i][this.colZ] || 0;
  461. var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer
  462. var yIndex = dataY.indexOf(y);
  463. if (dataMatrix[xIndex] === undefined) {
  464. dataMatrix[xIndex] = [];
  465. }
  466. var point3d = new Point3d();
  467. point3d.x = x;
  468. point3d.y = y;
  469. point3d.z = z;
  470. obj = {};
  471. obj.point = point3d;
  472. obj.trans = undefined;
  473. obj.screen = undefined;
  474. obj.bottom = new Point3d(x, y, this.zMin);
  475. dataMatrix[xIndex][yIndex] = obj;
  476. dataPoints.push(obj);
  477. }
  478. // fill in the pointers to the neighbors.
  479. for (x = 0; x < dataMatrix.length; x++) {
  480. for (y = 0; y < dataMatrix[x].length; y++) {
  481. if (dataMatrix[x][y]) {
  482. dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined;
  483. dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined;
  484. dataMatrix[x][y].pointCross =
  485. (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ?
  486. dataMatrix[x+1][y+1] :
  487. undefined;
  488. }
  489. }
  490. }
  491. }
  492. else { // 'dot', 'dot-line', etc.
  493. // copy all values from the google data table to a list with Point3d objects
  494. for (i = 0; i < data.length; i++) {
  495. point = new Point3d();
  496. point.x = data[i][this.colX] || 0;
  497. point.y = data[i][this.colY] || 0;
  498. point.z = data[i][this.colZ] || 0;
  499. if (this.colValue !== undefined) {
  500. point.value = data[i][this.colValue] || 0;
  501. }
  502. obj = {};
  503. obj.point = point;
  504. obj.bottom = new Point3d(point.x, point.y, this.zMin);
  505. obj.trans = undefined;
  506. obj.screen = undefined;
  507. dataPoints.push(obj);
  508. }
  509. }
  510. return dataPoints;
  511. };
  512. /**
  513. * Create the main frame for the Graph3d.
  514. * This function is executed once when a Graph3d object is created. The frame
  515. * contains a canvas, and this canvas contains all objects like the axis and
  516. * nodes.
  517. */
  518. Graph3d.prototype.create = function () {
  519. // remove all elements from the container element.
  520. while (this.containerElement.hasChildNodes()) {
  521. this.containerElement.removeChild(this.containerElement.firstChild);
  522. }
  523. this.frame = document.createElement('div');
  524. this.frame.style.position = 'relative';
  525. this.frame.style.overflow = 'hidden';
  526. // create the graph canvas (HTML canvas element)
  527. this.frame.canvas = document.createElement( 'canvas' );
  528. this.frame.canvas.style.position = 'relative';
  529. this.frame.appendChild(this.frame.canvas);
  530. //if (!this.frame.canvas.getContext) {
  531. {
  532. var noCanvas = document.createElement( 'DIV' );
  533. noCanvas.style.color = 'red';
  534. noCanvas.style.fontWeight = 'bold' ;
  535. noCanvas.style.padding = '10px';
  536. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  537. this.frame.canvas.appendChild(noCanvas);
  538. }
  539. this.frame.filter = document.createElement( 'div' );
  540. this.frame.filter.style.position = 'absolute';
  541. this.frame.filter.style.bottom = '0px';
  542. this.frame.filter.style.left = '0px';
  543. this.frame.filter.style.width = '100%';
  544. this.frame.appendChild(this.frame.filter);
  545. // add event listeners to handle moving and zooming the contents
  546. var me = this;
  547. var onmousedown = function (event) {me._onMouseDown(event);};
  548. var ontouchstart = function (event) {me._onTouchStart(event);};
  549. var onmousewheel = function (event) {me._onWheel(event);};
  550. var ontooltip = function (event) {me._onTooltip(event);};
  551. // TODO: these events are never cleaned up... can give a 'memory leakage'
  552. util.addEventListener(this.frame.canvas, 'keydown', onkeydown);
  553. util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
  554. util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
  555. util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
  556. util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
  557. // add the new graph to the container element
  558. this.containerElement.appendChild(this.frame);
  559. };
  560. /**
  561. * Set a new size for the graph
  562. * @param {string} width Width in pixels or percentage (for example '800px'
  563. * or '50%')
  564. * @param {string} height Height in pixels or percentage (for example '400px'
  565. * or '30%')
  566. */
  567. Graph3d.prototype.setSize = function(width, height) {
  568. this.frame.style.width = width;
  569. this.frame.style.height = height;
  570. this._resizeCanvas();
  571. };
  572. /**
  573. * Resize the canvas to the current size of the frame
  574. */
  575. Graph3d.prototype._resizeCanvas = function() {
  576. this.frame.canvas.style.width = '100%';
  577. this.frame.canvas.style.height = '100%';
  578. this.frame.canvas.width = this.frame.canvas.clientWidth;
  579. this.frame.canvas.height = this.frame.canvas.clientHeight;
  580. // adjust with for margin
  581. this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px';
  582. };
  583. /**
  584. * Start animation
  585. */
  586. Graph3d.prototype.animationStart = function() {
  587. if (!this.frame.filter || !this.frame.filter.slider)
  588. throw 'No animation available';
  589. this.frame.filter.slider.play();
  590. };
  591. /**
  592. * Stop animation
  593. */
  594. Graph3d.prototype.animationStop = function() {
  595. if (!this.frame.filter || !this.frame.filter.slider) return;
  596. this.frame.filter.slider.stop();
  597. };
  598. /**
  599. * Resize the center position based on the current values in this.defaultXCenter
  600. * and this.defaultYCenter (which are strings with a percentage or a value
  601. * in pixels). The center positions are the variables this.xCenter
  602. * and this.yCenter
  603. */
  604. Graph3d.prototype._resizeCenter = function() {
  605. // calculate the horizontal center position
  606. if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') {
  607. this.xcenter =
  608. parseFloat(this.defaultXCenter) / 100 *
  609. this.frame.canvas.clientWidth;
  610. }
  611. else {
  612. this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px
  613. }
  614. // calculate the vertical center position
  615. if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') {
  616. this.ycenter =
  617. parseFloat(this.defaultYCenter) / 100 *
  618. (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
  619. }
  620. else {
  621. this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px
  622. }
  623. };
  624. /**
  625. * Set the rotation and distance of the camera
  626. * @param {Object} pos An object with the camera position. The object
  627. * contains three parameters:
  628. * - horizontal {Number}
  629. * The horizontal rotation, between 0 and 2*PI.
  630. * Optional, can be left undefined.
  631. * - vertical {Number}
  632. * The vertical rotation, between 0 and 0.5*PI
  633. * if vertical=0.5*PI, the graph is shown from the
  634. * top. Optional, can be left undefined.
  635. * - distance {Number}
  636. * The (normalized) distance of the camera to the
  637. * center of the graph, a value between 0.71 and 5.0.
  638. * Optional, can be left undefined.
  639. */
  640. Graph3d.prototype.setCameraPosition = function(pos) {
  641. if (pos === undefined) {
  642. return;
  643. }
  644. if (pos.horizontal !== undefined && pos.vertical !== undefined) {
  645. this.camera.setArmRotation(pos.horizontal, pos.vertical);
  646. }
  647. if (pos.distance !== undefined) {
  648. this.camera.setArmLength(pos.distance);
  649. }
  650. this.redraw();
  651. };
  652. /**
  653. * Retrieve the current camera rotation
  654. * @return {object} An object with parameters horizontal, vertical, and
  655. * distance
  656. */
  657. Graph3d.prototype.getCameraPosition = function() {
  658. var pos = this.camera.getArmRotation();
  659. pos.distance = this.camera.getArmLength();
  660. return pos;
  661. };
  662. /**
  663. * Load data into the 3D Graph
  664. */
  665. Graph3d.prototype._readData = function(data) {
  666. // read the data
  667. this._dataInitialize(data, this.style);
  668. if (this.dataFilter) {
  669. // apply filtering
  670. this.dataPoints = this.dataFilter._getDataPoints();
  671. }
  672. else {
  673. // no filtering. load all data
  674. this.dataPoints = this._getDataPoints(this.dataTable);
  675. }
  676. // draw the filter
  677. this._redrawFilter();
  678. };
  679. /**
  680. * Replace the dataset of the Graph3d
  681. * @param {Array | DataSet | DataView} data
  682. */
  683. Graph3d.prototype.setData = function (data) {
  684. this._readData(data);
  685. this.redraw();
  686. // start animation when option is true
  687. if (this.animationAutoStart && this.dataFilter) {
  688. this.animationStart();
  689. }
  690. };
  691. /**
  692. * Update the options. Options will be merged with current options
  693. * @param {Object} options
  694. */
  695. Graph3d.prototype.setOptions = function (options) {
  696. var cameraPosition = undefined;
  697. this.animationStop();
  698. if (options !== undefined) {
  699. // retrieve parameter values
  700. if (options.width !== undefined) this.width = options.width;
  701. if (options.height !== undefined) this.height = options.height;
  702. if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter;
  703. if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter;
  704. if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel;
  705. if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel;
  706. if (options.xLabel !== undefined) this.xLabel = options.xLabel;
  707. if (options.yLabel !== undefined) this.yLabel = options.yLabel;
  708. if (options.zLabel !== undefined) this.zLabel = options.zLabel;
  709. if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel;
  710. if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel;
  711. if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel;
  712. if (options.style !== undefined) {
  713. var styleNumber = this._getStyleNumber(options.style);
  714. if (styleNumber !== -1) {
  715. this.style = styleNumber;
  716. }
  717. }
  718. if (options.showGrid !== undefined) this.showGrid = options.showGrid;
  719. if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective;
  720. if (options.showShadow !== undefined) this.showShadow = options.showShadow;
  721. if (options.tooltip !== undefined) this.showTooltip = options.tooltip;
  722. if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls;
  723. if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio;
  724. if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio;
  725. if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval;
  726. if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload;
  727. if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart;
  728. if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth;
  729. if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth;
  730. if (options.xMin !== undefined) this.defaultXMin = options.xMin;
  731. if (options.xStep !== undefined) this.defaultXStep = options.xStep;
  732. if (options.xMax !== undefined) this.defaultXMax = options.xMax;
  733. if (options.yMin !== undefined) this.defaultYMin = options.yMin;
  734. if (options.yStep !== undefined) this.defaultYStep = options.yStep;
  735. if (options.yMax !== undefined) this.defaultYMax = options.yMax;
  736. if (options.zMin !== undefined) this.defaultZMin = options.zMin;
  737. if (options.zStep !== undefined) this.defaultZStep = options.zStep;
  738. if (options.zMax !== undefined) this.defaultZMax = options.zMax;
  739. if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin;
  740. if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax;
  741. if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition;
  742. if (cameraPosition !== undefined) {
  743. this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical);
  744. this.camera.setArmLength(cameraPosition.distance);
  745. }
  746. else {
  747. this.camera.setArmRotation(1.0, 0.5);
  748. this.camera.setArmLength(1.7);
  749. }
  750. }
  751. this._setBackgroundColor(options && options.backgroundColor);
  752. this.setSize(this.width, this.height);
  753. // re-load the data
  754. if (this.dataTable) {
  755. this.setData(this.dataTable);
  756. }
  757. // start animation when option is true
  758. if (this.animationAutoStart && this.dataFilter) {
  759. this.animationStart();
  760. }
  761. };
  762. /**
  763. * Redraw the Graph.
  764. */
  765. Graph3d.prototype.redraw = function() {
  766. if (this.dataPoints === undefined) {
  767. throw 'Error: graph data not initialized';
  768. }
  769. this._resizeCanvas();
  770. this._resizeCenter();
  771. this._redrawSlider();
  772. this._redrawClear();
  773. this._redrawAxis();
  774. if (this.style === Graph3d.STYLE.GRID ||
  775. this.style === Graph3d.STYLE.SURFACE) {
  776. this._redrawDataGrid();
  777. }
  778. else if (this.style === Graph3d.STYLE.LINE) {
  779. this._redrawDataLine();
  780. }
  781. else if (this.style === Graph3d.STYLE.BAR ||
  782. this.style === Graph3d.STYLE.BARCOLOR ||
  783. this.style === Graph3d.STYLE.BARSIZE) {
  784. this._redrawDataBar();
  785. }
  786. else {
  787. // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE
  788. this._redrawDataDot();
  789. }
  790. this._redrawInfo();
  791. this._redrawLegend();
  792. };
  793. /**
  794. * Clear the canvas before redrawing
  795. */
  796. Graph3d.prototype._redrawClear = function() {
  797. var canvas = this.frame.canvas;
  798. var ctx = canvas.getContext('2d');
  799. ctx.clearRect(0, 0, canvas.width, canvas.height);
  800. };
  801. /**
  802. * Redraw the legend showing the colors
  803. */
  804. Graph3d.prototype._redrawLegend = function() {
  805. var y;
  806. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  807. this.style === Graph3d.STYLE.DOTSIZE) {
  808. var dotSize = this.frame.clientWidth * 0.02;
  809. var widthMin, widthMax;
  810. if (this.style === Graph3d.STYLE.DOTSIZE) {
  811. widthMin = dotSize / 2; // px
  812. widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function
  813. }
  814. else {
  815. widthMin = 20; // px
  816. widthMax = 20; // px
  817. }
  818. var height = Math.max(this.frame.clientHeight * 0.25, 100);
  819. var top = this.margin;
  820. var right = this.frame.clientWidth - this.margin;
  821. var left = right - widthMax;
  822. var bottom = top + height;
  823. }
  824. var canvas = this.frame.canvas;
  825. var ctx = canvas.getContext('2d');
  826. ctx.lineWidth = 1;
  827. ctx.font = '14px arial'; // TODO: put in options
  828. if (this.style === Graph3d.STYLE.DOTCOLOR) {
  829. // draw the color bar
  830. var ymin = 0;
  831. var ymax = height; // Todo: make height customizable
  832. for (y = ymin; y < ymax; y++) {
  833. var f = (y - ymin) / (ymax - ymin);
  834. //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function
  835. var hue = f * 240;
  836. var color = this._hsv2rgb(hue, 1, 1);
  837. ctx.strokeStyle = color;
  838. ctx.beginPath();
  839. ctx.moveTo(left, top + y);
  840. ctx.lineTo(right, top + y);
  841. ctx.stroke();
  842. }
  843. ctx.strokeStyle = this.colorAxis;
  844. ctx.strokeRect(left, top, widthMax, height);
  845. }
  846. if (this.style === Graph3d.STYLE.DOTSIZE) {
  847. // draw border around color bar
  848. ctx.strokeStyle = this.colorAxis;
  849. ctx.fillStyle = this.colorDot;
  850. ctx.beginPath();
  851. ctx.moveTo(left, top);
  852. ctx.lineTo(right, top);
  853. ctx.lineTo(right - widthMax + widthMin, bottom);
  854. ctx.lineTo(left, bottom);
  855. ctx.closePath();
  856. ctx.fill();
  857. ctx.stroke();
  858. }
  859. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  860. this.style === Graph3d.STYLE.DOTSIZE) {
  861. // print values along the color bar
  862. var gridLineLen = 5; // px
  863. var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true);
  864. step.start();
  865. if (step.getCurrent() < this.valueMin) {
  866. step.next();
  867. }
  868. while (!step.end()) {
  869. y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height;
  870. ctx.beginPath();
  871. ctx.moveTo(left - gridLineLen, y);
  872. ctx.lineTo(left, y);
  873. ctx.stroke();
  874. ctx.textAlign = 'right';
  875. ctx.textBaseline = 'middle';
  876. ctx.fillStyle = this.colorAxis;
  877. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  878. step.next();
  879. }
  880. ctx.textAlign = 'right';
  881. ctx.textBaseline = 'top';
  882. var label = this.legendLabel;
  883. ctx.fillText(label, right, bottom + this.margin);
  884. }
  885. };
  886. /**
  887. * Redraw the filter
  888. */
  889. Graph3d.prototype._redrawFilter = function() {
  890. this.frame.filter.innerHTML = '';
  891. if (this.dataFilter) {
  892. var options = {
  893. 'visible': this.showAnimationControls
  894. };
  895. var slider = new Slider(this.frame.filter, options);
  896. this.frame.filter.slider = slider;
  897. // TODO: css here is not nice here...
  898. this.frame.filter.style.padding = '10px';
  899. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  900. slider.setValues(this.dataFilter.values);
  901. slider.setPlayInterval(this.animationInterval);
  902. // create an event handler
  903. var me = this;
  904. var onchange = function () {
  905. var index = slider.getIndex();
  906. me.dataFilter.selectValue(index);
  907. me.dataPoints = me.dataFilter._getDataPoints();
  908. me.redraw();
  909. };
  910. slider.setOnChangeCallback(onchange);
  911. }
  912. else {
  913. this.frame.filter.slider = undefined;
  914. }
  915. };
  916. /**
  917. * Redraw the slider
  918. */
  919. Graph3d.prototype._redrawSlider = function() {
  920. if ( this.frame.filter.slider !== undefined) {
  921. this.frame.filter.slider.redraw();
  922. }
  923. };
  924. /**
  925. * Redraw common information
  926. */
  927. Graph3d.prototype._redrawInfo = function() {
  928. if (this.dataFilter) {
  929. var canvas = this.frame.canvas;
  930. var ctx = canvas.getContext('2d');
  931. ctx.font = '14px arial'; // TODO: put in options
  932. ctx.lineStyle = 'gray';
  933. ctx.fillStyle = 'gray';
  934. ctx.textAlign = 'left';
  935. ctx.textBaseline = 'top';
  936. var x = this.margin;
  937. var y = this.margin;
  938. ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y);
  939. }
  940. };
  941. /**
  942. * Redraw the axis
  943. */
  944. Graph3d.prototype._redrawAxis = function() {
  945. var canvas = this.frame.canvas,
  946. ctx = canvas.getContext('2d'),
  947. from, to, step, prettyStep,
  948. text, xText, yText, zText,
  949. offset, xOffset, yOffset,
  950. xMin2d, xMax2d;
  951. // TODO: get the actual rendered style of the containerElement
  952. //ctx.font = this.containerElement.style.font;
  953. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  954. // calculate the length for the short grid lines
  955. var gridLenX = 0.025 / this.scale.x;
  956. var gridLenY = 0.025 / this.scale.y;
  957. var textMargin = 5 / this.camera.getArmLength(); // px
  958. var armAngle = this.camera.getArmRotation().horizontal;
  959. // draw x-grid lines
  960. ctx.lineWidth = 1;
  961. prettyStep = (this.defaultXStep === undefined);
  962. step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep);
  963. step.start();
  964. if (step.getCurrent() < this.xMin) {
  965. step.next();
  966. }
  967. while (!step.end()) {
  968. var x = step.getCurrent();
  969. if (this.showGrid) {
  970. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  971. to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  972. ctx.strokeStyle = this.colorGrid;
  973. ctx.beginPath();
  974. ctx.moveTo(from.x, from.y);
  975. ctx.lineTo(to.x, to.y);
  976. ctx.stroke();
  977. }
  978. else {
  979. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  980. to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin));
  981. ctx.strokeStyle = this.colorAxis;
  982. ctx.beginPath();
  983. ctx.moveTo(from.x, from.y);
  984. ctx.lineTo(to.x, to.y);
  985. ctx.stroke();
  986. from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  987. to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin));
  988. ctx.strokeStyle = this.colorAxis;
  989. ctx.beginPath();
  990. ctx.moveTo(from.x, from.y);
  991. ctx.lineTo(to.x, to.y);
  992. ctx.stroke();
  993. }
  994. yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax;
  995. text = this._convert3Dto2D(new Point3d(x, yText, this.zMin));
  996. if (Math.cos(armAngle * 2) > 0) {
  997. ctx.textAlign = 'center';
  998. ctx.textBaseline = 'top';
  999. text.y += textMargin;
  1000. }
  1001. else if (Math.sin(armAngle * 2) < 0){
  1002. ctx.textAlign = 'right';
  1003. ctx.textBaseline = 'middle';
  1004. }
  1005. else {
  1006. ctx.textAlign = 'left';
  1007. ctx.textBaseline = 'middle';
  1008. }
  1009. ctx.fillStyle = this.colorAxis;
  1010. ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  1011. step.next();
  1012. }
  1013. // draw y-grid lines
  1014. ctx.lineWidth = 1;
  1015. prettyStep = (this.defaultYStep === undefined);
  1016. step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep);
  1017. step.start();
  1018. if (step.getCurrent() < this.yMin) {
  1019. step.next();
  1020. }
  1021. while (!step.end()) {
  1022. if (this.showGrid) {
  1023. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  1024. to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  1025. ctx.strokeStyle = this.colorGrid;
  1026. ctx.beginPath();
  1027. ctx.moveTo(from.x, from.y);
  1028. ctx.lineTo(to.x, to.y);
  1029. ctx.stroke();
  1030. }
  1031. else {
  1032. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  1033. to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin));
  1034. ctx.strokeStyle = this.colorAxis;
  1035. ctx.beginPath();
  1036. ctx.moveTo(from.x, from.y);
  1037. ctx.lineTo(to.x, to.y);
  1038. ctx.stroke();
  1039. from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  1040. to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin));
  1041. ctx.strokeStyle = this.colorAxis;
  1042. ctx.beginPath();
  1043. ctx.moveTo(from.x, from.y);
  1044. ctx.lineTo(to.x, to.y);
  1045. ctx.stroke();
  1046. }
  1047. xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax;
  1048. text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin));
  1049. if (Math.cos(armAngle * 2) < 0) {
  1050. ctx.textAlign = 'center';
  1051. ctx.textBaseline = 'top';
  1052. text.y += textMargin;
  1053. }
  1054. else if (Math.sin(armAngle * 2) > 0){
  1055. ctx.textAlign = 'right';
  1056. ctx.textBaseline = 'middle';
  1057. }
  1058. else {
  1059. ctx.textAlign = 'left';
  1060. ctx.textBaseline = 'middle';
  1061. }
  1062. ctx.fillStyle = this.colorAxis;
  1063. ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  1064. step.next();
  1065. }
  1066. // draw z-grid lines and axis
  1067. ctx.lineWidth = 1;
  1068. prettyStep = (this.defaultZStep === undefined);
  1069. step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep);
  1070. step.start();
  1071. if (step.getCurrent() < this.zMin) {
  1072. step.next();
  1073. }
  1074. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  1075. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  1076. while (!step.end()) {
  1077. // TODO: make z-grid lines really 3d?
  1078. from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent()));
  1079. ctx.strokeStyle = this.colorAxis;
  1080. ctx.beginPath();
  1081. ctx.moveTo(from.x, from.y);
  1082. ctx.lineTo(from.x - textMargin, from.y);
  1083. ctx.stroke();
  1084. ctx.textAlign = 'right';
  1085. ctx.textBaseline = 'middle';
  1086. ctx.fillStyle = this.colorAxis;
  1087. ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y);
  1088. step.next();
  1089. }
  1090. ctx.lineWidth = 1;
  1091. from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  1092. to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax));
  1093. ctx.strokeStyle = this.colorAxis;
  1094. ctx.beginPath();
  1095. ctx.moveTo(from.x, from.y);
  1096. ctx.lineTo(to.x, to.y);
  1097. ctx.stroke();
  1098. // draw x-axis
  1099. ctx.lineWidth = 1;
  1100. // line at yMin
  1101. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  1102. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  1103. ctx.strokeStyle = this.colorAxis;
  1104. ctx.beginPath();
  1105. ctx.moveTo(xMin2d.x, xMin2d.y);
  1106. ctx.lineTo(xMax2d.x, xMax2d.y);
  1107. ctx.stroke();
  1108. // line at ymax
  1109. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  1110. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  1111. ctx.strokeStyle = this.colorAxis;
  1112. ctx.beginPath();
  1113. ctx.moveTo(xMin2d.x, xMin2d.y);
  1114. ctx.lineTo(xMax2d.x, xMax2d.y);
  1115. ctx.stroke();
  1116. // draw y-axis
  1117. ctx.lineWidth = 1;
  1118. // line at xMin
  1119. from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  1120. to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  1121. ctx.strokeStyle = this.colorAxis;
  1122. ctx.beginPath();
  1123. ctx.moveTo(from.x, from.y);
  1124. ctx.lineTo(to.x, to.y);
  1125. ctx.stroke();
  1126. // line at xMax
  1127. from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  1128. to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  1129. ctx.strokeStyle = this.colorAxis;
  1130. ctx.beginPath();
  1131. ctx.moveTo(from.x, from.y);
  1132. ctx.lineTo(to.x, to.y);
  1133. ctx.stroke();
  1134. // draw x-label
  1135. var xLabel = this.xLabel;
  1136. if (xLabel.length > 0) {
  1137. yOffset = 0.1 / this.scale.y;
  1138. xText = (this.xMin + this.xMax) / 2;
  1139. yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset;
  1140. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  1141. if (Math.cos(armAngle * 2) > 0) {
  1142. ctx.textAlign = 'center';
  1143. ctx.textBaseline = 'top';
  1144. }
  1145. else if (Math.sin(armAngle * 2) < 0){
  1146. ctx.textAlign = 'right';
  1147. ctx.textBaseline = 'middle';
  1148. }
  1149. else {
  1150. ctx.textAlign = 'left';
  1151. ctx.textBaseline = 'middle';
  1152. }
  1153. ctx.fillStyle = this.colorAxis;
  1154. ctx.fillText(xLabel, text.x, text.y);
  1155. }
  1156. // draw y-label
  1157. var yLabel = this.yLabel;
  1158. if (yLabel.length > 0) {
  1159. xOffset = 0.1 / this.scale.x;
  1160. xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset;
  1161. yText = (this.yMin + this.yMax) / 2;
  1162. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  1163. if (Math.cos(armAngle * 2) < 0) {
  1164. ctx.textAlign = 'center';
  1165. ctx.textBaseline = 'top';
  1166. }
  1167. else if (Math.sin(armAngle * 2) > 0){
  1168. ctx.textAlign = 'right';
  1169. ctx.textBaseline = 'middle';
  1170. }
  1171. else {
  1172. ctx.textAlign = 'left';
  1173. ctx.textBaseline = 'middle';
  1174. }
  1175. ctx.fillStyle = this.colorAxis;
  1176. ctx.fillText(yLabel, text.x, text.y);
  1177. }
  1178. // draw z-label
  1179. var zLabel = this.zLabel;
  1180. if (zLabel.length > 0) {
  1181. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  1182. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  1183. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  1184. zText = (this.zMin + this.zMax) / 2;
  1185. text = this._convert3Dto2D(new Point3d(xText, yText, zText));
  1186. ctx.textAlign = 'right';
  1187. ctx.textBaseline = 'middle';
  1188. ctx.fillStyle = this.colorAxis;
  1189. ctx.fillText(zLabel, text.x - offset, text.y);
  1190. }
  1191. };
  1192. /**
  1193. * Calculate the color based on the given value.
  1194. * @param {Number} H Hue, a value be between 0 and 360
  1195. * @param {Number} S Saturation, a value between 0 and 1
  1196. * @param {Number} V Value, a value between 0 and 1
  1197. */
  1198. Graph3d.prototype._hsv2rgb = function(H, S, V) {
  1199. var R, G, B, C, Hi, X;
  1200. C = V * S;
  1201. Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5
  1202. X = C * (1 - Math.abs(((H/60) % 2) - 1));
  1203. switch (Hi) {
  1204. case 0: R = C; G = X; B = 0; break;
  1205. case 1: R = X; G = C; B = 0; break;
  1206. case 2: R = 0; G = C; B = X; break;
  1207. case 3: R = 0; G = X; B = C; break;
  1208. case 4: R = X; G = 0; B = C; break;
  1209. case 5: R = C; G = 0; B = X; break;
  1210. default: R = 0; G = 0; B = 0; break;
  1211. }
  1212. return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')';
  1213. };
  1214. /**
  1215. * Draw all datapoints as a grid
  1216. * This function can be used when the style is 'grid'
  1217. */
  1218. Graph3d.prototype._redrawDataGrid = function() {
  1219. var canvas = this.frame.canvas,
  1220. ctx = canvas.getContext('2d'),
  1221. point, right, top, cross,
  1222. i,
  1223. topSideVisible, fillStyle, strokeStyle, lineWidth,
  1224. h, s, v, zAvg;
  1225. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1226. return; // TODO: throw exception?
  1227. // calculate the translations and screen position of all points
  1228. for (i = 0; i < this.dataPoints.length; i++) {
  1229. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  1230. var screen = this._convertTranslationToScreen(trans);
  1231. this.dataPoints[i].trans = trans;
  1232. this.dataPoints[i].screen = screen;
  1233. // calculate the translation of the point at the bottom (needed for sorting)
  1234. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  1235. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  1236. }
  1237. // sort the points on depth of their (x,y) position (not on z)
  1238. var sortDepth = function (a, b) {
  1239. return b.dist - a.dist;
  1240. };
  1241. this.dataPoints.sort(sortDepth);
  1242. if (this.style === Graph3d.STYLE.SURFACE) {
  1243. for (i = 0; i < this.dataPoints.length; i++) {
  1244. point = this.dataPoints[i];
  1245. right = this.dataPoints[i].pointRight;
  1246. top = this.dataPoints[i].pointTop;
  1247. cross = this.dataPoints[i].pointCross;
  1248. if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) {
  1249. if (this.showGrayBottom || this.showShadow) {
  1250. // calculate the cross product of the two vectors from center
  1251. // to left and right, in order to know whether we are looking at the
  1252. // bottom or at the top side. We can also use the cross product
  1253. // for calculating light intensity
  1254. var aDiff = Point3d.subtract(cross.trans, point.trans);
  1255. var bDiff = Point3d.subtract(top.trans, right.trans);
  1256. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  1257. var len = crossproduct.length();
  1258. // FIXME: there is a bug with determining the surface side (shadow or colored)
  1259. topSideVisible = (crossproduct.z > 0);
  1260. }
  1261. else {
  1262. topSideVisible = true;
  1263. }
  1264. if (topSideVisible) {
  1265. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1266. zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  1267. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  1268. s = 1; // saturation
  1269. if (this.showShadow) {
  1270. v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale
  1271. fillStyle = this._hsv2rgb(h, s, v);
  1272. strokeStyle = fillStyle;
  1273. }
  1274. else {
  1275. v = 1;
  1276. fillStyle = this._hsv2rgb(h, s, v);
  1277. strokeStyle = this.colorAxis;
  1278. }
  1279. }
  1280. else {
  1281. fillStyle = 'gray';
  1282. strokeStyle = this.colorAxis;
  1283. }
  1284. lineWidth = 0.5;
  1285. ctx.lineWidth = lineWidth;
  1286. ctx.fillStyle = fillStyle;
  1287. ctx.strokeStyle = strokeStyle;
  1288. ctx.beginPath();
  1289. ctx.moveTo(point.screen.x, point.screen.y);
  1290. ctx.lineTo(right.screen.x, right.screen.y);
  1291. ctx.lineTo(cross.screen.x, cross.screen.y);
  1292. ctx.lineTo(top.screen.x, top.screen.y);
  1293. ctx.closePath();
  1294. ctx.fill();
  1295. ctx.stroke();
  1296. }
  1297. }
  1298. }
  1299. else { // grid style
  1300. for (i = 0; i < this.dataPoints.length; i++) {
  1301. point = this.dataPoints[i];
  1302. right = this.dataPoints[i].pointRight;
  1303. top = this.dataPoints[i].pointTop;
  1304. if (point !== undefined) {
  1305. if (this.showPerspective) {
  1306. lineWidth = 2 / -point.trans.z;
  1307. }
  1308. else {
  1309. lineWidth = 2 * -(this.eye.z / this.camera.getArmLength());
  1310. }
  1311. }
  1312. if (point !== undefined && right !== undefined) {
  1313. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1314. zAvg = (point.point.z + right.point.z) / 2;
  1315. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  1316. ctx.lineWidth = lineWidth;
  1317. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  1318. ctx.beginPath();
  1319. ctx.moveTo(point.screen.x, point.screen.y);
  1320. ctx.lineTo(right.screen.x, right.screen.y);
  1321. ctx.stroke();
  1322. }
  1323. if (point !== undefined && top !== undefined) {
  1324. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1325. zAvg = (point.point.z + top.point.z) / 2;
  1326. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  1327. ctx.lineWidth = lineWidth;
  1328. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  1329. ctx.beginPath();
  1330. ctx.moveTo(point.screen.x, point.screen.y);
  1331. ctx.lineTo(top.screen.x, top.screen.y);
  1332. ctx.stroke();
  1333. }
  1334. }
  1335. }
  1336. };
  1337. /**
  1338. * Draw all datapoints as dots.
  1339. * This function can be used when the style is 'dot' or 'dot-line'
  1340. */
  1341. Graph3d.prototype._redrawDataDot = function() {
  1342. var canvas = this.frame.canvas;
  1343. var ctx = canvas.getContext('2d');
  1344. var i;
  1345. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1346. return; // TODO: throw exception?
  1347. // calculate the translations of all points
  1348. for (i = 0; i < this.dataPoints.length; i++) {
  1349. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  1350. var screen = this._convertTranslationToScreen(trans);
  1351. this.dataPoints[i].trans = trans;
  1352. this.dataPoints[i].screen = screen;
  1353. // calculate the distance from the point at the bottom to the camera
  1354. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  1355. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  1356. }
  1357. // order the translated points by depth
  1358. var sortDepth = function (a, b) {
  1359. return b.dist - a.dist;
  1360. };
  1361. this.dataPoints.sort(sortDepth);
  1362. // draw the datapoints as colored circles
  1363. var dotSize = this.frame.clientWidth * 0.02; // px
  1364. for (i = 0; i < this.dataPoints.length; i++) {
  1365. var point = this.dataPoints[i];
  1366. if (this.style === Graph3d.STYLE.DOTLINE) {
  1367. // draw a vertical line from the bottom to the graph value
  1368. //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin));
  1369. var from = this._convert3Dto2D(point.bottom);
  1370. ctx.lineWidth = 1;
  1371. ctx.strokeStyle = this.colorGrid;
  1372. ctx.beginPath();
  1373. ctx.moveTo(from.x, from.y);
  1374. ctx.lineTo(point.screen.x, point.screen.y);
  1375. ctx.stroke();
  1376. }
  1377. // calculate radius for the circle
  1378. var size;
  1379. if (this.style === Graph3d.STYLE.DOTSIZE) {
  1380. size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin);
  1381. }
  1382. else {
  1383. size = dotSize;
  1384. }
  1385. var radius;
  1386. if (this.showPerspective) {
  1387. radius = size / -point.trans.z;
  1388. }
  1389. else {
  1390. radius = size * -(this.eye.z / this.camera.getArmLength());
  1391. }
  1392. if (radius < 0) {
  1393. radius = 0;
  1394. }
  1395. var hue, color, borderColor;
  1396. if (this.style === Graph3d.STYLE.DOTCOLOR ) {
  1397. // calculate the color based on the value
  1398. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  1399. color = this._hsv2rgb(hue, 1, 1);
  1400. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1401. }
  1402. else if (this.style === Graph3d.STYLE.DOTSIZE) {
  1403. color = this.colorDot;
  1404. borderColor = this.colorDotBorder;
  1405. }
  1406. else {
  1407. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1408. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  1409. color = this._hsv2rgb(hue, 1, 1);
  1410. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1411. }
  1412. // draw the circle
  1413. ctx.lineWidth = 1.0;
  1414. ctx.strokeStyle = borderColor;
  1415. ctx.fillStyle = color;
  1416. ctx.beginPath();
  1417. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true);
  1418. ctx.fill();
  1419. ctx.stroke();
  1420. }
  1421. };
  1422. /**
  1423. * Draw all datapoints as bars.
  1424. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size'
  1425. */
  1426. Graph3d.prototype._redrawDataBar = function() {
  1427. var canvas = this.frame.canvas;
  1428. var ctx = canvas.getContext('2d');
  1429. var i, j, surface, corners;
  1430. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1431. return; // TODO: throw exception?
  1432. // calculate the translations of all points
  1433. for (i = 0; i < this.dataPoints.length; i++) {
  1434. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  1435. var screen = this._convertTranslationToScreen(trans);
  1436. this.dataPoints[i].trans = trans;
  1437. this.dataPoints[i].screen = screen;
  1438. // calculate the distance from the point at the bottom to the camera
  1439. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  1440. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  1441. }
  1442. // order the translated points by depth
  1443. var sortDepth = function (a, b) {
  1444. return b.dist - a.dist;
  1445. };
  1446. this.dataPoints.sort(sortDepth);
  1447. // draw the datapoints as bars
  1448. var xWidth = this.xBarWidth / 2;
  1449. var yWidth = this.yBarWidth / 2;
  1450. for (i = 0; i < this.dataPoints.length; i++) {
  1451. var point = this.dataPoints[i];
  1452. // determine color
  1453. var hue, color, borderColor;
  1454. if (this.style === Graph3d.STYLE.BARCOLOR ) {
  1455. // calculate the color based on the value
  1456. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  1457. color = this._hsv2rgb(hue, 1, 1);
  1458. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1459. }
  1460. else if (this.style === Graph3d.STYLE.BARSIZE) {
  1461. color = this.colorDot;
  1462. borderColor = this.colorDotBorder;
  1463. }
  1464. else {
  1465. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1466. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  1467. color = this._hsv2rgb(hue, 1, 1);
  1468. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1469. }
  1470. // calculate size for the bar
  1471. if (this.style === Graph3d.STYLE.BARSIZE) {
  1472. xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  1473. yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  1474. }
  1475. // calculate all corner points
  1476. var me = this;
  1477. var point3d = point.point;
  1478. var top = [
  1479. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)},
  1480. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)},
  1481. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)},
  1482. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)}
  1483. ];
  1484. var bottom = [
  1485. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)},
  1486. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)},
  1487. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)},
  1488. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)}
  1489. ];
  1490. // calculate screen location of the points
  1491. top.forEach(function (obj) {
  1492. obj.screen = me._convert3Dto2D(obj.point);
  1493. });
  1494. bottom.forEach(function (obj) {
  1495. obj.screen = me._convert3Dto2D(obj.point);
  1496. });
  1497. // create five sides, calculate both corner points and center points
  1498. var surfaces = [
  1499. {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)},
  1500. {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)},
  1501. {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)},
  1502. {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)},
  1503. {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)}
  1504. ];
  1505. point.surfaces = surfaces;
  1506. // calculate the distance of each of the surface centers to the camera
  1507. for (j = 0; j < surfaces.length; j++) {
  1508. surface = surfaces[j];
  1509. var transCenter = this._convertPointToTranslation(surface.center);
  1510. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  1511. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  1512. // but the current solution is fast/simple and works in 99.9% of all cases
  1513. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  1514. }
  1515. // order the surfaces by their (translated) depth
  1516. surfaces.sort(function (a, b) {
  1517. var diff = b.dist - a.dist;
  1518. if (diff) return diff;
  1519. // if equal depth, sort the top surface last
  1520. if (a.corners === top) return 1;
  1521. if (b.corners === top) return -1;
  1522. // both are equal
  1523. return 0;
  1524. });
  1525. // draw the ordered surfaces
  1526. ctx.lineWidth = 1;
  1527. ctx.strokeStyle = borderColor;
  1528. ctx.fillStyle = color;
  1529. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  1530. for (j = 2; j < surfaces.length; j++) {
  1531. surface = surfaces[j];
  1532. corners = surface.corners;
  1533. ctx.beginPath();
  1534. ctx.moveTo(corners[3].screen.x, corners[3].screen.y);
  1535. ctx.lineTo(corners[0].screen.x, corners[0].screen.y);
  1536. ctx.lineTo(corners[1].screen.x, corners[1].screen.y);
  1537. ctx.lineTo(corners[2].screen.x, corners[2].screen.y);
  1538. ctx.lineTo(corners[3].screen.x, corners[3].screen.y);
  1539. ctx.fill();
  1540. ctx.stroke();
  1541. }
  1542. }
  1543. };
  1544. /**
  1545. * Draw a line through all datapoints.
  1546. * This function can be used when the style is 'line'
  1547. */
  1548. Graph3d.prototype._redrawDataLine = function() {
  1549. var canvas = this.frame.canvas,
  1550. ctx = canvas.getContext('2d'),
  1551. point, i;
  1552. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1553. return; // TODO: throw exception?
  1554. // calculate the translations of all points
  1555. for (i = 0; i < this.dataPoints.length; i++) {
  1556. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  1557. var screen = this._convertTranslationToScreen(trans);
  1558. this.dataPoints[i].trans = trans;
  1559. this.dataPoints[i].screen = screen;
  1560. }
  1561. // start the line
  1562. if (this.dataPoints.length > 0) {
  1563. point = this.dataPoints[0];
  1564. ctx.lineWidth = 1; // TODO: make customizable
  1565. ctx.strokeStyle = 'blue'; // TODO: make customizable
  1566. ctx.beginPath();
  1567. ctx.moveTo(point.screen.x, point.screen.y);
  1568. }
  1569. // draw the datapoints as colored circles
  1570. for (i = 1; i < this.dataPoints.length; i++) {
  1571. point = this.dataPoints[i];
  1572. ctx.lineTo(point.screen.x, point.screen.y);
  1573. }
  1574. // finish the line
  1575. if (this.dataPoints.length > 0) {
  1576. ctx.stroke();
  1577. }
  1578. };
  1579. /**
  1580. * Start a moving operation inside the provided parent element
  1581. * @param {Event} event The event that occurred (required for
  1582. * retrieving the mouse position)
  1583. */
  1584. Graph3d.prototype._onMouseDown = function(event) {
  1585. event = event || window.event;
  1586. // check if mouse is still down (may be up when focus is lost for example
  1587. // in an iframe)
  1588. if (this.leftButtonDown) {
  1589. this._onMouseUp(event);
  1590. }
  1591. // only react on left mouse button down
  1592. this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  1593. if (!this.leftButtonDown && !this.touchDown) return;
  1594. // get mouse position (different code for IE and all other browsers)
  1595. this.startMouseX = getMouseX(event);
  1596. this.startMouseY = getMouseY(event);
  1597. this.startStart = new Date(this.start);
  1598. this.startEnd = new Date(this.end);
  1599. this.startArmRotation = this.camera.getArmRotation();
  1600. this.frame.style.cursor = 'move';
  1601. // add event listeners to handle moving the contents
  1602. // we store the function onmousemove and onmouseup in the graph, so we can
  1603. // remove the eventlisteners lateron in the function mouseUp()
  1604. var me = this;
  1605. this.onmousemove = function (event) {me._onMouseMove(event);};
  1606. this.onmouseup = function (event) {me._onMouseUp(event);};
  1607. util.addEventListener(document, 'mousemove', me.onmousemove);
  1608. util.addEventListener(document, 'mouseup', me.onmouseup);
  1609. util.preventDefault(event);
  1610. };
  1611. /**
  1612. * Perform moving operating.
  1613. * This function activated from within the funcion Graph.mouseDown().
  1614. * @param {Event} event Well, eehh, the event
  1615. */
  1616. Graph3d.prototype._onMouseMove = function (event) {
  1617. event = event || window.event;
  1618. // calculate change in mouse position
  1619. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  1620. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  1621. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  1622. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  1623. var snapAngle = 4; // degrees
  1624. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  1625. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  1626. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  1627. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  1628. horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001;
  1629. }
  1630. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  1631. horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001;
  1632. }
  1633. // snap vertically to nice angles
  1634. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  1635. verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI;
  1636. }
  1637. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  1638. verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI;
  1639. }
  1640. this.camera.setArmRotation(horizontalNew, verticalNew);
  1641. this.redraw();
  1642. // fire a cameraPositionChange event
  1643. var parameters = this.getCameraPosition();
  1644. this.emit('cameraPositionChange', parameters);
  1645. util.preventDefault(event);
  1646. };
  1647. /**
  1648. * Stop moving operating.
  1649. * This function activated from within the funcion Graph.mouseDown().
  1650. * @param {event} event The event
  1651. */
  1652. Graph3d.prototype._onMouseUp = function (event) {
  1653. this.frame.style.cursor = 'auto';
  1654. this.leftButtonDown = false;
  1655. // remove event listeners here
  1656. util.removeEventListener(document, 'mousemove', this.onmousemove);
  1657. util.removeEventListener(document, 'mouseup', this.onmouseup);
  1658. util.preventDefault(event);
  1659. };
  1660. /**
  1661. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  1662. * @param {Event} event A mouse move event
  1663. */
  1664. Graph3d.prototype._onTooltip = function (event) {
  1665. var delay = 300; // ms
  1666. var mouseX = getMouseX(event) - util.getAbsoluteLeft(this.frame);
  1667. var mouseY = getMouseY(event) - util.getAbsoluteTop(this.frame);
  1668. if (!this.showTooltip) {
  1669. return;
  1670. }
  1671. if (this.tooltipTimeout) {
  1672. clearTimeout(this.tooltipTimeout);
  1673. }
  1674. // (delayed) display of a tooltip only if no mouse button is down
  1675. if (this.leftButtonDown) {
  1676. this._hideTooltip();
  1677. return;
  1678. }
  1679. if (this.tooltip && this.tooltip.dataPoint) {
  1680. // tooltip is currently visible
  1681. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  1682. if (dataPoint !== this.tooltip.dataPoint) {
  1683. // datapoint changed
  1684. if (dataPoint) {
  1685. this._showTooltip(dataPoint);
  1686. }
  1687. else {
  1688. this._hideTooltip();
  1689. }
  1690. }
  1691. }
  1692. else {
  1693. // tooltip is currently not visible
  1694. var me = this;
  1695. this.tooltipTimeout = setTimeout(function () {
  1696. me.tooltipTimeout = null;
  1697. // show a tooltip if we have a data point
  1698. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  1699. if (dataPoint) {
  1700. me._showTooltip(dataPoint);
  1701. }
  1702. }, delay);
  1703. }
  1704. };
  1705. /**
  1706. * Event handler for touchstart event on mobile devices
  1707. */
  1708. Graph3d.prototype._onTouchStart = function(event) {
  1709. this.touchDown = true;
  1710. var me = this;
  1711. this.ontouchmove = function (event) {me._onTouchMove(event);};
  1712. this.ontouchend = function (event) {me._onTouchEnd(event);};
  1713. util.addEventListener(document, 'touchmove', me.ontouchmove);
  1714. util.addEventListener(document, 'touchend', me.ontouchend);
  1715. this._onMouseDown(event);
  1716. };
  1717. /**
  1718. * Event handler for touchmove event on mobile devices
  1719. */
  1720. Graph3d.prototype._onTouchMove = function(event) {
  1721. this._onMouseMove(event);
  1722. };
  1723. /**
  1724. * Event handler for touchend event on mobile devices
  1725. */
  1726. Graph3d.prototype._onTouchEnd = function(event) {
  1727. this.touchDown = false;
  1728. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  1729. util.removeEventListener(document, 'touchend', this.ontouchend);
  1730. this._onMouseUp(event);
  1731. };
  1732. /**
  1733. * Event handler for mouse wheel event, used to zoom the graph
  1734. * Code from http://adomas.org/javascript-mouse-wheel/
  1735. * @param {event} event The event
  1736. */
  1737. Graph3d.prototype._onWheel = function(event) {
  1738. if (!event) /* For IE. */
  1739. event = window.event;
  1740. // retrieve delta
  1741. var delta = 0;
  1742. if (event.wheelDelta) { /* IE/Opera. */
  1743. delta = event.wheelDelta/120;
  1744. } else if (event.detail) { /* Mozilla case. */
  1745. // In Mozilla, sign of delta is different than in IE.
  1746. // Also, delta is multiple of 3.
  1747. delta = -event.detail/3;
  1748. }
  1749. // If delta is nonzero, handle it.
  1750. // Basically, delta is now positive if wheel was scrolled up,
  1751. // and negative, if wheel was scrolled down.
  1752. if (delta) {
  1753. var oldLength = this.camera.getArmLength();
  1754. var newLength = oldLength * (1 - delta / 10);
  1755. this.camera.setArmLength(newLength);
  1756. this.redraw();
  1757. this._hideTooltip();
  1758. }
  1759. // fire a cameraPositionChange event
  1760. var parameters = this.getCameraPosition();
  1761. this.emit('cameraPositionChange', parameters);
  1762. // Prevent default actions caused by mouse wheel.
  1763. // That might be ugly, but we handle scrolls somehow
  1764. // anyway, so don't bother here..
  1765. util.preventDefault(event);
  1766. };
  1767. /**
  1768. * Test whether a point lies inside given 2D triangle
  1769. * @param {Point2d} point
  1770. * @param {Point2d[]} triangle
  1771. * @return {boolean} Returns true if given point lies inside or on the edge of the triangle
  1772. * @private
  1773. */
  1774. Graph3d.prototype._insideTriangle = function (point, triangle) {
  1775. var a = triangle[0],
  1776. b = triangle[1],
  1777. c = triangle[2];
  1778. function sign (x) {
  1779. return x > 0 ? 1 : x < 0 ? -1 : 0;
  1780. }
  1781. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  1782. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  1783. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  1784. // each of the three signs must be either equal to each other or zero
  1785. return (as == 0 || bs == 0 || as == bs) &&
  1786. (bs == 0 || cs == 0 || bs == cs) &&
  1787. (as == 0 || cs == 0 || as == cs);
  1788. };
  1789. /**
  1790. * Find a data point close to given screen position (x, y)
  1791. * @param {Number} x
  1792. * @param {Number} y
  1793. * @return {Object | null} The closest data point or null if not close to any data point
  1794. * @private
  1795. */
  1796. Graph3d.prototype._dataPointFromXY = function (x, y) {
  1797. var i,
  1798. distMax = 100, // px
  1799. dataPoint = null,
  1800. closestDataPoint = null,
  1801. closestDist = null,
  1802. center = new Point2d(x, y);
  1803. if (this.style === Graph3d.STYLE.BAR ||
  1804. this.style === Graph3d.STYLE.BARCOLOR ||
  1805. this.style === Graph3d.STYLE.BARSIZE) {
  1806. // the data points are ordered from far away to closest
  1807. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  1808. dataPoint = this.dataPoints[i];
  1809. var surfaces = dataPoint.surfaces;
  1810. if (surfaces) {
  1811. for (var s = surfaces.length - 1; s >= 0; s--) {
  1812. // split each surface in two triangles, and see if the center point is inside one of these
  1813. var surface = surfaces[s];
  1814. var corners = surface.corners;
  1815. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  1816. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  1817. if (this._insideTriangle(center, triangle1) ||
  1818. this._insideTriangle(center, triangle2)) {
  1819. // return immediately at the first hit
  1820. return dataPoint;
  1821. }
  1822. }
  1823. }
  1824. }
  1825. }
  1826. else {
  1827. // find the closest data point, using distance to the center of the point on 2d screen
  1828. for (i = 0; i < this.dataPoints.length; i++) {
  1829. dataPoint = this.dataPoints[i];
  1830. var point = dataPoint.screen;
  1831. if (point) {
  1832. var distX = Math.abs(x - point.x);
  1833. var distY = Math.abs(y - point.y);
  1834. var dist = Math.sqrt(distX * distX + distY * distY);
  1835. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  1836. closestDist = dist;
  1837. closestDataPoint = dataPoint;
  1838. }
  1839. }
  1840. }
  1841. }
  1842. return closestDataPoint;
  1843. };
  1844. /**
  1845. * Display a tooltip for given data point
  1846. * @param {Object} dataPoint
  1847. * @private
  1848. */
  1849. Graph3d.prototype._showTooltip = function (dataPoint) {
  1850. var content, line, dot;
  1851. if (!this.tooltip) {
  1852. content = document.createElement('div');
  1853. content.style.position = 'absolute';
  1854. content.style.padding = '10px';
  1855. content.style.border = '1px solid #4d4d4d';
  1856. content.style.color = '#1a1a1a';
  1857. content.style.background = 'rgba(255,255,255,0.7)';
  1858. content.style.borderRadius = '2px';
  1859. content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)';
  1860. line = document.createElement('div');
  1861. line.style.position = 'absolute';
  1862. line.style.height = '40px';
  1863. line.style.width = '0';
  1864. line.style.borderLeft = '1px solid #4d4d4d';
  1865. dot = document.createElement('div');
  1866. dot.style.position = 'absolute';
  1867. dot.style.height = '0';
  1868. dot.style.width = '0';
  1869. dot.style.border = '5px solid #4d4d4d';
  1870. dot.style.borderRadius = '5px';
  1871. this.tooltip = {
  1872. dataPoint: null,
  1873. dom: {
  1874. content: content,
  1875. line: line,
  1876. dot: dot
  1877. }
  1878. };
  1879. }
  1880. else {
  1881. content = this.tooltip.dom.content;
  1882. line = this.tooltip.dom.line;
  1883. dot = this.tooltip.dom.dot;
  1884. }
  1885. this._hideTooltip();
  1886. this.tooltip.dataPoint = dataPoint;
  1887. if (typeof this.showTooltip === 'function') {
  1888. content.innerHTML = this.showTooltip(dataPoint.point);
  1889. }
  1890. else {
  1891. content.innerHTML = '<table>' +
  1892. '<tr><td>x:</td><td>' + dataPoint.point.x + '</td></tr>' +
  1893. '<tr><td>y:</td><td>' + dataPoint.point.y + '</td></tr>' +
  1894. '<tr><td>z:</td><td>' + dataPoint.point.z + '</td></tr>' +
  1895. '</table>';
  1896. }
  1897. content.style.left = '0';
  1898. content.style.top = '0';
  1899. this.frame.appendChild(content);
  1900. this.frame.appendChild(line);
  1901. this.frame.appendChild(dot);
  1902. // calculate sizes
  1903. var contentWidth = content.offsetWidth;
  1904. var contentHeight = content.offsetHeight;
  1905. var lineHeight = line.offsetHeight;
  1906. var dotWidth = dot.offsetWidth;
  1907. var dotHeight = dot.offsetHeight;
  1908. var left = dataPoint.screen.x - contentWidth / 2;
  1909. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  1910. line.style.left = dataPoint.screen.x + 'px';
  1911. line.style.top = (dataPoint.screen.y - lineHeight) + 'px';
  1912. content.style.left = left + 'px';
  1913. content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px';
  1914. dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px';
  1915. dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px';
  1916. };
  1917. /**
  1918. * Hide the tooltip when displayed
  1919. * @private
  1920. */
  1921. Graph3d.prototype._hideTooltip = function () {
  1922. if (this.tooltip) {
  1923. this.tooltip.dataPoint = null;
  1924. for (var prop in this.tooltip.dom) {
  1925. if (this.tooltip.dom.hasOwnProperty(prop)) {
  1926. var elem = this.tooltip.dom[prop];
  1927. if (elem && elem.parentNode) {
  1928. elem.parentNode.removeChild(elem);
  1929. }
  1930. }
  1931. }
  1932. }
  1933. };
  1934. /**--------------------------------------------------------------------------**/
  1935. /**
  1936. * Get the horizontal mouse position from a mouse event
  1937. * @param {Event} event
  1938. * @return {Number} mouse x
  1939. */
  1940. getMouseX = function(event) {
  1941. if ('clientX' in event) return event.clientX;
  1942. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  1943. };
  1944. /**
  1945. * Get the vertical mouse position from a mouse event
  1946. * @param {Event} event
  1947. * @return {Number} mouse y
  1948. */
  1949. getMouseY = function(event) {
  1950. if ('clientY' in event) return event.clientY;
  1951. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  1952. };
  1953. module.exports = Graph3d;