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.

2197 lines
64 KiB

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