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.

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