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.

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