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.

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