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.

2191 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. var from;
  814. var to;
  815. while (!step.end()) {
  816. y = bottom - (step.getCurrent() - legendMin) / (legendMax - legendMin) * height;
  817. from = new Point2d(left - gridLineLen, y);
  818. to = new Point2d(left, y);
  819. this._line(ctx, from, to);
  820. ctx.textAlign = 'right';
  821. ctx.textBaseline = 'middle';
  822. ctx.fillStyle = this.axisColor;
  823. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  824. step.next();
  825. }
  826. ctx.textAlign = 'right';
  827. ctx.textBaseline = 'top';
  828. var label = this.legendLabel;
  829. ctx.fillText(label, right, bottom + this.margin);
  830. };
  831. /**
  832. * Redraw the filter
  833. */
  834. Graph3d.prototype._redrawFilter = function() {
  835. this.frame.filter.innerHTML = '';
  836. if (this.dataFilter) {
  837. var options = {
  838. 'visible': this.showAnimationControls
  839. };
  840. var slider = new Slider(this.frame.filter, options);
  841. this.frame.filter.slider = slider;
  842. // TODO: css here is not nice here...
  843. this.frame.filter.style.padding = '10px';
  844. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  845. slider.setValues(this.dataFilter.values);
  846. slider.setPlayInterval(this.animationInterval);
  847. // create an event handler
  848. var me = this;
  849. var onchange = function () {
  850. var index = slider.getIndex();
  851. me.dataFilter.selectValue(index);
  852. me.dataPoints = me.dataFilter._getDataPoints();
  853. me.redraw();
  854. };
  855. slider.setOnChangeCallback(onchange);
  856. }
  857. else {
  858. this.frame.filter.slider = undefined;
  859. }
  860. };
  861. /**
  862. * Redraw the slider
  863. */
  864. Graph3d.prototype._redrawSlider = function() {
  865. if ( this.frame.filter.slider !== undefined) {
  866. this.frame.filter.slider.redraw();
  867. }
  868. };
  869. /**
  870. * Redraw common information
  871. */
  872. Graph3d.prototype._redrawInfo = function() {
  873. if (this.dataFilter) {
  874. var ctx = this._getContext();
  875. ctx.font = '14px arial'; // TODO: put in options
  876. ctx.lineStyle = 'gray';
  877. ctx.fillStyle = 'gray';
  878. ctx.textAlign = 'left';
  879. ctx.textBaseline = 'top';
  880. var x = this.margin;
  881. var y = this.margin;
  882. ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y);
  883. }
  884. };
  885. /**
  886. * Draw a line between 2d points 'from' and 'to'.
  887. *
  888. * If stroke style specified, set that as well.
  889. */
  890. Graph3d.prototype._line = function(ctx, from, to, strokeStyle) {
  891. if (strokeStyle !== undefined) {
  892. ctx.strokeStyle = strokeStyle;
  893. }
  894. ctx.beginPath();
  895. ctx.moveTo(from.x, from.y);
  896. ctx.lineTo(to.x , to.y );
  897. ctx.stroke();
  898. }
  899. Graph3d.prototype.drawAxisLabelX = function(ctx, point3d, text, armAngle, yMargin) {
  900. if (yMargin === undefined) {
  901. yMargin = 0;
  902. }
  903. var point2d = this._convert3Dto2D(point3d);
  904. if (Math.cos(armAngle * 2) > 0) {
  905. ctx.textAlign = 'center';
  906. ctx.textBaseline = 'top';
  907. point2d.y += yMargin;
  908. }
  909. else if (Math.sin(armAngle * 2) < 0){
  910. ctx.textAlign = 'right';
  911. ctx.textBaseline = 'middle';
  912. }
  913. else {
  914. ctx.textAlign = 'left';
  915. ctx.textBaseline = 'middle';
  916. }
  917. ctx.fillStyle = this.axisColor;
  918. ctx.fillText(text, point2d.x, point2d.y);
  919. }
  920. Graph3d.prototype.drawAxisLabelY = function(ctx, point3d, text, armAngle, yMargin) {
  921. if (yMargin === undefined) {
  922. yMargin = 0;
  923. }
  924. var point2d = this._convert3Dto2D(point3d);
  925. if (Math.cos(armAngle * 2) < 0) {
  926. ctx.textAlign = 'center';
  927. ctx.textBaseline = 'top';
  928. point2d.y += yMargin;
  929. }
  930. else if (Math.sin(armAngle * 2) > 0){
  931. ctx.textAlign = 'right';
  932. ctx.textBaseline = 'middle';
  933. }
  934. else {
  935. ctx.textAlign = 'left';
  936. ctx.textBaseline = 'middle';
  937. }
  938. ctx.fillStyle = this.axisColor;
  939. ctx.fillText(text, point2d.x, point2d.y);
  940. }
  941. Graph3d.prototype.drawAxisLabelZ = function(ctx, point3d, text, offset) {
  942. if (offset === undefined) {
  943. offset = 0;
  944. }
  945. var point2d = this._convert3Dto2D(point3d);
  946. ctx.textAlign = 'right';
  947. ctx.textBaseline = 'middle';
  948. ctx.fillStyle = this.axisColor;
  949. ctx.fillText(text, point2d.x - offset, point2d.y);
  950. };
  951. /**
  952. /**
  953. * Draw a line between 2d points 'from' and 'to'.
  954. *
  955. * If stroke style specified, set that as well.
  956. */
  957. Graph3d.prototype._line3d = function(ctx, from, to, strokeStyle) {
  958. var from2d = this._convert3Dto2D(from);
  959. var to2d = this._convert3Dto2D(to);
  960. this._line(ctx, from2d, to2d, strokeStyle);
  961. }
  962. /**
  963. * Redraw the axis
  964. */
  965. Graph3d.prototype._redrawAxis = function() {
  966. var ctx = this._getContext(),
  967. from, to, step, prettyStep,
  968. text, xText, yText, zText,
  969. offset, xOffset, yOffset,
  970. xMin2d, xMax2d;
  971. // TODO: get the actual rendered style of the containerElement
  972. //ctx.font = this.containerElement.style.font;
  973. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  974. // calculate the length for the short grid lines
  975. var gridLenX = 0.025 / this.scale.x;
  976. var gridLenY = 0.025 / this.scale.y;
  977. var textMargin = 5 / this.camera.getArmLength(); // px
  978. var armAngle = this.camera.getArmRotation().horizontal;
  979. var armVector = new Point2d(Math.cos(armAngle), Math.sin(armAngle));
  980. // draw x-grid lines
  981. ctx.lineWidth = 1;
  982. prettyStep = (this.defaultXStep === undefined);
  983. step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep);
  984. step.start(true);
  985. while (!step.end()) {
  986. var x = step.getCurrent();
  987. if (this.showGrid) {
  988. from = new Point3d(x, this.yMin, this.zMin);
  989. to = new Point3d(x, this.yMax, this.zMin);
  990. this._line3d(ctx, from, to, this.gridColor);
  991. }
  992. else {
  993. from = new Point3d(x, this.yMin, this.zMin);
  994. to = new Point3d(x, this.yMin+gridLenX, this.zMin);
  995. this._line3d(ctx, from, to, this.axisColor);
  996. from = new Point3d(x, this.yMax, this.zMin);
  997. to = new Point3d(x, this.yMax-gridLenX, this.zMin);
  998. this._line3d(ctx, from, to, this.axisColor);
  999. }
  1000. yText = (armVector.x > 0) ? this.yMin : this.yMax;
  1001. var point3d = new Point3d(x, yText, this.zMin);
  1002. var msg = ' ' + this.xValueLabel(x) + ' ';
  1003. this.drawAxisLabelX(ctx, point3d, msg, armAngle, textMargin);
  1004. step.next();
  1005. }
  1006. // draw y-grid lines
  1007. ctx.lineWidth = 1;
  1008. prettyStep = (this.defaultYStep === undefined);
  1009. step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep);
  1010. step.start(true);
  1011. while (!step.end()) {
  1012. var y = step.getCurrent();
  1013. if (this.showGrid) {
  1014. from = new Point3d(this.xMin, y, this.zMin);
  1015. to = new Point3d(this.xMax, y, this.zMin);
  1016. this._line3d(ctx, from, to, this.gridColor);
  1017. }
  1018. else {
  1019. from = new Point3d(this.xMin, y, this.zMin);
  1020. to = new Point3d(this.xMin+gridLenY, y, this.zMin);
  1021. this._line3d(ctx, from, to, this.axisColor);
  1022. from = new Point3d(this.xMax, y, this.zMin);
  1023. to = new Point3d(this.xMax-gridLenY, y, this.zMin);
  1024. this._line3d(ctx, from, to, this.axisColor);
  1025. }
  1026. xText = (armVector.y > 0) ? this.xMin : this.xMax;
  1027. point3d = new Point3d(xText, y, this.zMin);
  1028. var msg = ' ' + this.yValueLabel(y) + ' ';
  1029. this.drawAxisLabelY(ctx, point3d, msg, armAngle, textMargin);
  1030. step.next();
  1031. }
  1032. // draw z-grid lines and axis
  1033. ctx.lineWidth = 1;
  1034. prettyStep = (this.defaultZStep === undefined);
  1035. step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep);
  1036. step.start(true);
  1037. xText = (armVector.x > 0) ? this.xMin : this.xMax;
  1038. yText = (armVector.y < 0) ? this.yMin : this.yMax;
  1039. while (!step.end()) {
  1040. var z = step.getCurrent();
  1041. // TODO: make z-grid lines really 3d?
  1042. var from3d = new Point3d(xText, yText, z);
  1043. var from2d = this._convert3Dto2D(from3d);
  1044. to = new Point2d(from2d.x - textMargin, from2d.y);
  1045. this._line(ctx, from2d, to, this.axisColor);
  1046. var msg = this.zValueLabel(z) + ' ';
  1047. this.drawAxisLabelZ(ctx, from3d, msg, 5);
  1048. step.next();
  1049. }
  1050. ctx.lineWidth = 1;
  1051. from = new Point3d(xText, yText, this.zMin);
  1052. to = new Point3d(xText, yText, this.zMax);
  1053. this._line3d(ctx, from, to, this.axisColor);
  1054. // draw x-axis
  1055. ctx.lineWidth = 1;
  1056. // line at yMin
  1057. xMin2d = new Point3d(this.xMin, this.yMin, this.zMin);
  1058. xMax2d = new Point3d(this.xMax, this.yMin, this.zMin);
  1059. this._line3d(ctx, xMin2d, xMax2d, this.axisColor);
  1060. // line at ymax
  1061. xMin2d = new Point3d(this.xMin, this.yMax, this.zMin);
  1062. xMax2d = new Point3d(this.xMax, this.yMax, this.zMin);
  1063. this._line3d(ctx, xMin2d, xMax2d, this.axisColor);
  1064. // draw y-axis
  1065. ctx.lineWidth = 1;
  1066. // line at xMin
  1067. from = new Point3d(this.xMin, this.yMin, this.zMin);
  1068. to = new Point3d(this.xMin, this.yMax, this.zMin);
  1069. this._line3d(ctx, from, to, this.axisColor);
  1070. // line at xMax
  1071. from = new Point3d(this.xMax, this.yMin, this.zMin);
  1072. to = new Point3d(this.xMax, this.yMax, this.zMin);
  1073. this._line3d(ctx, from, to, this.axisColor);
  1074. // draw x-label
  1075. var xLabel = this.xLabel;
  1076. if (xLabel.length > 0) {
  1077. yOffset = 0.1 / this.scale.y;
  1078. xText = (this.xMin + this.xMax) / 2;
  1079. yText = (armVector.x > 0) ? this.yMin - yOffset: this.yMax + yOffset;
  1080. text = new Point3d(xText, yText, this.zMin);
  1081. this.drawAxisLabelX(ctx, text, xLabel, armAngle);
  1082. }
  1083. // draw y-label
  1084. var yLabel = this.yLabel;
  1085. if (yLabel.length > 0) {
  1086. xOffset = 0.1 / this.scale.x;
  1087. xText = (armVector.y > 0) ? this.xMin - xOffset : this.xMax + xOffset;
  1088. yText = (this.yMin + this.yMax) / 2;
  1089. text = new Point3d(xText, yText, this.zMin);
  1090. this.drawAxisLabelY(ctx, text, yLabel, armAngle);
  1091. }
  1092. // draw z-label
  1093. var zLabel = this.zLabel;
  1094. if (zLabel.length > 0) {
  1095. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  1096. xText = (armVector.x > 0) ? this.xMin : this.xMax;
  1097. yText = (armVector.y < 0) ? this.yMin : this.yMax;
  1098. zText = (this.zMin + this.zMax) / 2;
  1099. text = new Point3d(xText, yText, zText);
  1100. this.drawAxisLabelZ(ctx, text, zLabel, offset);
  1101. }
  1102. };
  1103. /**
  1104. * Calculate the color based on the given value.
  1105. * @param {Number} H Hue, a value be between 0 and 360
  1106. * @param {Number} S Saturation, a value between 0 and 1
  1107. * @param {Number} V Value, a value between 0 and 1
  1108. */
  1109. Graph3d.prototype._hsv2rgb = function(H, S, V) {
  1110. var R, G, B, C, Hi, X;
  1111. C = V * S;
  1112. Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5
  1113. X = C * (1 - Math.abs(((H/60) % 2) - 1));
  1114. switch (Hi) {
  1115. case 0: R = C; G = X; B = 0; break;
  1116. case 1: R = X; G = C; B = 0; break;
  1117. case 2: R = 0; G = C; B = X; break;
  1118. case 3: R = 0; G = X; B = C; break;
  1119. case 4: R = X; G = 0; B = C; break;
  1120. case 5: R = C; G = 0; B = X; break;
  1121. default: R = 0; G = 0; B = 0; break;
  1122. }
  1123. return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')';
  1124. };
  1125. Graph3d.prototype._drawGridLine = function(ctx, from, to) {
  1126. if (from === undefined || to === undefined) {
  1127. return;
  1128. }
  1129. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1130. var zAvg = (from.point.z + to.point.z) / 2;
  1131. var h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  1132. ctx.lineWidth = this._getStrokeWidth(from) * 2;
  1133. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  1134. this._line(ctx, from.screen, to.screen);
  1135. };
  1136. /**
  1137. * Draw all datapoints as a grid
  1138. * This function can be used when the style is 'grid'
  1139. */
  1140. Graph3d.prototype._redrawDataGrid = function() {
  1141. var ctx = this._getContext(),
  1142. point, right, top, cross,
  1143. i,
  1144. topSideVisible, fillStyle, strokeStyle, lineWidth,
  1145. h, s, v, zAvg;
  1146. ctx.lineJoin = 'round';
  1147. ctx.lineCap = 'round';
  1148. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1149. return; // TODO: throw exception?
  1150. this._calcTranslations(this.dataPoints);
  1151. if (this.style === Graph3d.STYLE.SURFACE) {
  1152. for (i = 0; i < this.dataPoints.length; i++) {
  1153. point = this.dataPoints[i];
  1154. right = point.pointRight;
  1155. top = point.pointTop;
  1156. cross = point.pointCross;
  1157. if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) {
  1158. if (this.showGrayBottom || this.showShadow) {
  1159. // calculate the cross product of the two vectors from center
  1160. // to left and right, in order to know whether we are looking at the
  1161. // bottom or at the top side. We can also use the cross product
  1162. // for calculating light intensity
  1163. var aDiff = Point3d.subtract(cross.trans, point.trans);
  1164. var bDiff = Point3d.subtract(top.trans, right.trans);
  1165. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  1166. var len = crossproduct.length();
  1167. // FIXME: there is a bug with determining the surface side (shadow or colored)
  1168. topSideVisible = (crossproduct.z > 0);
  1169. }
  1170. else {
  1171. topSideVisible = true;
  1172. }
  1173. if (topSideVisible) {
  1174. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1175. zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  1176. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  1177. s = 1; // saturation
  1178. if (this.showShadow) {
  1179. v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale
  1180. fillStyle = this._hsv2rgb(h, s, v);
  1181. strokeStyle = fillStyle;
  1182. }
  1183. else {
  1184. v = 1;
  1185. fillStyle = this._hsv2rgb(h, s, v);
  1186. strokeStyle = this.axisColor; // TODO: should be customizable
  1187. }
  1188. }
  1189. else {
  1190. fillStyle = 'gray';
  1191. strokeStyle = this.axisColor;
  1192. }
  1193. ctx.lineWidth = this._getStrokeWidth(point);
  1194. ctx.fillStyle = fillStyle;
  1195. ctx.strokeStyle = strokeStyle;
  1196. ctx.beginPath();
  1197. ctx.moveTo(point.screen.x, point.screen.y);
  1198. ctx.lineTo(right.screen.x, right.screen.y);
  1199. ctx.lineTo(cross.screen.x, cross.screen.y);
  1200. ctx.lineTo(top.screen.x, top.screen.y);
  1201. ctx.closePath();
  1202. ctx.fill();
  1203. ctx.stroke(); // TODO: only draw stroke when strokeWidth > 0
  1204. }
  1205. }
  1206. }
  1207. else { // grid style
  1208. for (i = 0; i < this.dataPoints.length; i++) {
  1209. point = this.dataPoints[i];
  1210. this._drawGridLine(ctx, point, point.pointRight);
  1211. this._drawGridLine(ctx, point, point.pointTop);
  1212. }
  1213. }
  1214. };
  1215. Graph3d.prototype._getStrokeWidth = function(point) {
  1216. if (point !== undefined) {
  1217. if (this.showPerspective) {
  1218. return 1 / -point.trans.z * this.dataColor.strokeWidth;
  1219. }
  1220. else {
  1221. return -(this.eye.z / this.camera.getArmLength()) * this.dataColor.strokeWidth;
  1222. }
  1223. }
  1224. return this.dataColor.strokeWidth;
  1225. };
  1226. /**
  1227. * Draw all datapoints as dots.
  1228. * This function can be used when the style is 'dot' or 'dot-line'
  1229. */
  1230. Graph3d.prototype._redrawDataDot = function() {
  1231. var ctx = this._getContext();
  1232. var i;
  1233. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1234. return; // TODO: throw exception?
  1235. this._calcTranslations(this.dataPoints);
  1236. // draw the datapoints as colored circles
  1237. var dotSize = this.frame.clientWidth * this.dotSizeRatio; // px
  1238. for (i = 0; i < this.dataPoints.length; i++) {
  1239. var point = this.dataPoints[i];
  1240. if (this.style === Graph3d.STYLE.DOTLINE) {
  1241. // draw a vertical line from the bottom to the graph value
  1242. //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin));
  1243. var from = this._convert3Dto2D(point.bottom);
  1244. ctx.lineWidth = 1;
  1245. this._line(ctx, from, point.screen, this.gridColor);
  1246. }
  1247. // calculate radius for the circle
  1248. var size;
  1249. if (this.style === Graph3d.STYLE.DOTSIZE) {
  1250. size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin);
  1251. }
  1252. else {
  1253. size = dotSize;
  1254. }
  1255. var radius;
  1256. if (this.showPerspective) {
  1257. radius = size / -point.trans.z;
  1258. }
  1259. else {
  1260. radius = size * -(this.eye.z / this.camera.getArmLength());
  1261. }
  1262. if (radius < 0) {
  1263. radius = 0;
  1264. }
  1265. var hue, color, borderColor;
  1266. if (this.style === Graph3d.STYLE.DOTCOLOR ) {
  1267. // calculate the color based on the value
  1268. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  1269. color = this._hsv2rgb(hue, 1, 1);
  1270. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1271. }
  1272. else if (this.style === Graph3d.STYLE.DOTSIZE) {
  1273. color = this.dataColor.fill;
  1274. borderColor = this.dataColor.stroke;
  1275. }
  1276. else {
  1277. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1278. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  1279. color = this._hsv2rgb(hue, 1, 1);
  1280. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1281. }
  1282. // draw the circle
  1283. ctx.lineWidth = this._getStrokeWidth(point);
  1284. ctx.strokeStyle = borderColor;
  1285. ctx.fillStyle = color;
  1286. ctx.beginPath();
  1287. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true);
  1288. ctx.fill();
  1289. ctx.stroke();
  1290. }
  1291. };
  1292. /**
  1293. * Draw all datapoints as bars.
  1294. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size'
  1295. */
  1296. Graph3d.prototype._redrawDataBar = function() {
  1297. var ctx = this._getContext();
  1298. var i, j, surface, corners;
  1299. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1300. return; // TODO: throw exception?
  1301. this._calcTranslations(this.dataPoints);
  1302. ctx.lineJoin = 'round';
  1303. ctx.lineCap = 'round';
  1304. // draw the datapoints as bars
  1305. var xWidth = this.xBarWidth / 2;
  1306. var yWidth = this.yBarWidth / 2;
  1307. for (i = 0; i < this.dataPoints.length; i++) {
  1308. var point = this.dataPoints[i];
  1309. // determine color
  1310. var hue, color, borderColor;
  1311. if (this.style === Graph3d.STYLE.BARCOLOR ) {
  1312. // calculate the color based on the value
  1313. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  1314. color = this._hsv2rgb(hue, 1, 1);
  1315. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1316. }
  1317. else if (this.style === Graph3d.STYLE.BARSIZE) {
  1318. color = this.dataColor.fill;
  1319. borderColor = this.dataColor.stroke;
  1320. }
  1321. else {
  1322. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1323. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  1324. color = this._hsv2rgb(hue, 1, 1);
  1325. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1326. }
  1327. // calculate size for the bar
  1328. if (this.style === Graph3d.STYLE.BARSIZE) {
  1329. xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  1330. yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  1331. }
  1332. // calculate all corner points
  1333. var me = this;
  1334. var point3d = point.point;
  1335. var top = [
  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. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)},
  1339. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)}
  1340. ];
  1341. var bottom = [
  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. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)},
  1345. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)}
  1346. ];
  1347. // calculate screen location of the points
  1348. top.forEach(function (obj) {
  1349. obj.screen = me._convert3Dto2D(obj.point);
  1350. });
  1351. bottom.forEach(function (obj) {
  1352. obj.screen = me._convert3Dto2D(obj.point);
  1353. });
  1354. // create five sides, calculate both corner points and center points
  1355. var surfaces = [
  1356. {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)},
  1357. {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)},
  1358. {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)},
  1359. {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)},
  1360. {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)}
  1361. ];
  1362. point.surfaces = surfaces;
  1363. // calculate the distance of each of the surface centers to the camera
  1364. for (j = 0; j < surfaces.length; j++) {
  1365. surface = surfaces[j];
  1366. var transCenter = this._convertPointToTranslation(surface.center);
  1367. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  1368. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  1369. // but the current solution is fast/simple and works in 99.9% of all cases
  1370. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  1371. }
  1372. // order the surfaces by their (translated) depth
  1373. surfaces.sort(function (a, b) {
  1374. var diff = b.dist - a.dist;
  1375. if (diff) return diff;
  1376. // if equal depth, sort the top surface last
  1377. if (a.corners === top) return 1;
  1378. if (b.corners === top) return -1;
  1379. // both are equal
  1380. return 0;
  1381. });
  1382. // draw the ordered surfaces
  1383. ctx.lineWidth = this._getStrokeWidth(point);
  1384. ctx.strokeStyle = borderColor;
  1385. ctx.fillStyle = color;
  1386. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  1387. for (j = 2; j < surfaces.length; j++) {
  1388. surface = surfaces[j];
  1389. corners = surface.corners;
  1390. ctx.beginPath();
  1391. ctx.moveTo(corners[3].screen.x, corners[3].screen.y);
  1392. ctx.lineTo(corners[0].screen.x, corners[0].screen.y);
  1393. ctx.lineTo(corners[1].screen.x, corners[1].screen.y);
  1394. ctx.lineTo(corners[2].screen.x, corners[2].screen.y);
  1395. ctx.lineTo(corners[3].screen.x, corners[3].screen.y);
  1396. ctx.fill();
  1397. ctx.stroke();
  1398. }
  1399. }
  1400. };
  1401. /**
  1402. * Draw a line through all datapoints.
  1403. * This function can be used when the style is 'line'
  1404. */
  1405. Graph3d.prototype._redrawDataLine = function() {
  1406. var ctx = this._getContext(),
  1407. point, i;
  1408. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1409. return; // TODO: throw exception?
  1410. this._calcTranslations(this.dataPoints);
  1411. // start the line
  1412. if (this.dataPoints.length > 0) {
  1413. point = this.dataPoints[0];
  1414. ctx.lineWidth = this._getStrokeWidth(point);
  1415. ctx.lineJoin = 'round';
  1416. ctx.lineCap = 'round';
  1417. ctx.strokeStyle = this.dataColor.stroke;
  1418. for (i = 0; i < this.dataPoints.length; i++) {
  1419. point = this.dataPoints[i];
  1420. if (point.pointNext !== undefined) {
  1421. this._line(ctx, point.screen, point.pointNext.screen);
  1422. }
  1423. }
  1424. }
  1425. };
  1426. /**
  1427. * Start a moving operation inside the provided parent element
  1428. * @param {Event} event The event that occurred (required for
  1429. * retrieving the mouse position)
  1430. */
  1431. Graph3d.prototype._onMouseDown = function(event) {
  1432. event = event || window.event;
  1433. // check if mouse is still down (may be up when focus is lost for example
  1434. // in an iframe)
  1435. if (this.leftButtonDown) {
  1436. this._onMouseUp(event);
  1437. }
  1438. // only react on left mouse button down
  1439. this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  1440. if (!this.leftButtonDown && !this.touchDown) return;
  1441. // get mouse position (different code for IE and all other browsers)
  1442. this.startMouseX = getMouseX(event);
  1443. this.startMouseY = getMouseY(event);
  1444. this.startStart = new Date(this.start);
  1445. this.startEnd = new Date(this.end);
  1446. this.startArmRotation = this.camera.getArmRotation();
  1447. this.frame.style.cursor = 'move';
  1448. // add event listeners to handle moving the contents
  1449. // we store the function onmousemove and onmouseup in the graph, so we can
  1450. // remove the eventlisteners lateron in the function mouseUp()
  1451. var me = this;
  1452. this.onmousemove = function (event) {me._onMouseMove(event);};
  1453. this.onmouseup = function (event) {me._onMouseUp(event);};
  1454. util.addEventListener(document, 'mousemove', me.onmousemove);
  1455. util.addEventListener(document, 'mouseup', me.onmouseup);
  1456. util.preventDefault(event);
  1457. };
  1458. /**
  1459. * Perform moving operating.
  1460. * This function activated from within the funcion Graph.mouseDown().
  1461. * @param {Event} event Well, eehh, the event
  1462. */
  1463. Graph3d.prototype._onMouseMove = function (event) {
  1464. event = event || window.event;
  1465. // calculate change in mouse position
  1466. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  1467. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  1468. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  1469. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  1470. var snapAngle = 4; // degrees
  1471. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  1472. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  1473. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  1474. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  1475. horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001;
  1476. }
  1477. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  1478. horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001;
  1479. }
  1480. // snap vertically to nice angles
  1481. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  1482. verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI;
  1483. }
  1484. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  1485. verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI;
  1486. }
  1487. this.camera.setArmRotation(horizontalNew, verticalNew);
  1488. this.redraw();
  1489. // fire a cameraPositionChange event
  1490. var parameters = this.getCameraPosition();
  1491. this.emit('cameraPositionChange', parameters);
  1492. util.preventDefault(event);
  1493. };
  1494. /**
  1495. * Stop moving operating.
  1496. * This function activated from within the funcion Graph.mouseDown().
  1497. * @param {event} event The event
  1498. */
  1499. Graph3d.prototype._onMouseUp = function (event) {
  1500. this.frame.style.cursor = 'auto';
  1501. this.leftButtonDown = false;
  1502. // remove event listeners here
  1503. util.removeEventListener(document, 'mousemove', this.onmousemove);
  1504. util.removeEventListener(document, 'mouseup', this.onmouseup);
  1505. util.preventDefault(event);
  1506. };
  1507. /**
  1508. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  1509. * @param {Event} event A mouse move event
  1510. */
  1511. Graph3d.prototype._onTooltip = function (event) {
  1512. var delay = 300; // ms
  1513. var boundingRect = this.frame.getBoundingClientRect();
  1514. var mouseX = getMouseX(event) - boundingRect.left;
  1515. var mouseY = getMouseY(event) - boundingRect.top;
  1516. if (!this.showTooltip) {
  1517. return;
  1518. }
  1519. if (this.tooltipTimeout) {
  1520. clearTimeout(this.tooltipTimeout);
  1521. }
  1522. // (delayed) display of a tooltip only if no mouse button is down
  1523. if (this.leftButtonDown) {
  1524. this._hideTooltip();
  1525. return;
  1526. }
  1527. if (this.tooltip && this.tooltip.dataPoint) {
  1528. // tooltip is currently visible
  1529. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  1530. if (dataPoint !== this.tooltip.dataPoint) {
  1531. // datapoint changed
  1532. if (dataPoint) {
  1533. this._showTooltip(dataPoint);
  1534. }
  1535. else {
  1536. this._hideTooltip();
  1537. }
  1538. }
  1539. }
  1540. else {
  1541. // tooltip is currently not visible
  1542. var me = this;
  1543. this.tooltipTimeout = setTimeout(function () {
  1544. me.tooltipTimeout = null;
  1545. // show a tooltip if we have a data point
  1546. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  1547. if (dataPoint) {
  1548. me._showTooltip(dataPoint);
  1549. }
  1550. }, delay);
  1551. }
  1552. };
  1553. /**
  1554. * Event handler for touchstart event on mobile devices
  1555. */
  1556. Graph3d.prototype._onTouchStart = function(event) {
  1557. this.touchDown = true;
  1558. var me = this;
  1559. this.ontouchmove = function (event) {me._onTouchMove(event);};
  1560. this.ontouchend = function (event) {me._onTouchEnd(event);};
  1561. util.addEventListener(document, 'touchmove', me.ontouchmove);
  1562. util.addEventListener(document, 'touchend', me.ontouchend);
  1563. this._onMouseDown(event);
  1564. };
  1565. /**
  1566. * Event handler for touchmove event on mobile devices
  1567. */
  1568. Graph3d.prototype._onTouchMove = function(event) {
  1569. this._onMouseMove(event);
  1570. };
  1571. /**
  1572. * Event handler for touchend event on mobile devices
  1573. */
  1574. Graph3d.prototype._onTouchEnd = function(event) {
  1575. this.touchDown = false;
  1576. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  1577. util.removeEventListener(document, 'touchend', this.ontouchend);
  1578. this._onMouseUp(event);
  1579. };
  1580. /**
  1581. * Event handler for mouse wheel event, used to zoom the graph
  1582. * Code from http://adomas.org/javascript-mouse-wheel/
  1583. * @param {event} event The event
  1584. */
  1585. Graph3d.prototype._onWheel = function(event) {
  1586. if (!event) /* For IE. */
  1587. event = window.event;
  1588. // retrieve delta
  1589. var delta = 0;
  1590. if (event.wheelDelta) { /* IE/Opera. */
  1591. delta = event.wheelDelta/120;
  1592. } else if (event.detail) { /* Mozilla case. */
  1593. // In Mozilla, sign of delta is different than in IE.
  1594. // Also, delta is multiple of 3.
  1595. delta = -event.detail/3;
  1596. }
  1597. // If delta is nonzero, handle it.
  1598. // Basically, delta is now positive if wheel was scrolled up,
  1599. // and negative, if wheel was scrolled down.
  1600. if (delta) {
  1601. var oldLength = this.camera.getArmLength();
  1602. var newLength = oldLength * (1 - delta / 10);
  1603. this.camera.setArmLength(newLength);
  1604. this.redraw();
  1605. this._hideTooltip();
  1606. }
  1607. // fire a cameraPositionChange event
  1608. var parameters = this.getCameraPosition();
  1609. this.emit('cameraPositionChange', parameters);
  1610. // Prevent default actions caused by mouse wheel.
  1611. // That might be ugly, but we handle scrolls somehow
  1612. // anyway, so don't bother here..
  1613. util.preventDefault(event);
  1614. };
  1615. /**
  1616. * Test whether a point lies inside given 2D triangle
  1617. * @param {Point2d} point
  1618. * @param {Point2d[]} triangle
  1619. * @return {boolean} Returns true if given point lies inside or on the edge of the triangle
  1620. * @private
  1621. */
  1622. Graph3d.prototype._insideTriangle = function (point, triangle) {
  1623. var a = triangle[0],
  1624. b = triangle[1],
  1625. c = triangle[2];
  1626. function sign (x) {
  1627. return x > 0 ? 1 : x < 0 ? -1 : 0;
  1628. }
  1629. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  1630. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  1631. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  1632. // each of the three signs must be either equal to each other or zero
  1633. return (as == 0 || bs == 0 || as == bs) &&
  1634. (bs == 0 || cs == 0 || bs == cs) &&
  1635. (as == 0 || cs == 0 || as == cs);
  1636. };
  1637. /**
  1638. * Find a data point close to given screen position (x, y)
  1639. * @param {Number} x
  1640. * @param {Number} y
  1641. * @return {Object | null} The closest data point or null if not close to any data point
  1642. * @private
  1643. */
  1644. Graph3d.prototype._dataPointFromXY = function (x, y) {
  1645. var i,
  1646. distMax = 100, // px
  1647. dataPoint = null,
  1648. closestDataPoint = null,
  1649. closestDist = null,
  1650. center = new Point2d(x, y);
  1651. if (this.style === Graph3d.STYLE.BAR ||
  1652. this.style === Graph3d.STYLE.BARCOLOR ||
  1653. this.style === Graph3d.STYLE.BARSIZE) {
  1654. // the data points are ordered from far away to closest
  1655. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  1656. dataPoint = this.dataPoints[i];
  1657. var surfaces = dataPoint.surfaces;
  1658. if (surfaces) {
  1659. for (var s = surfaces.length - 1; s >= 0; s--) {
  1660. // split each surface in two triangles, and see if the center point is inside one of these
  1661. var surface = surfaces[s];
  1662. var corners = surface.corners;
  1663. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  1664. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  1665. if (this._insideTriangle(center, triangle1) ||
  1666. this._insideTriangle(center, triangle2)) {
  1667. // return immediately at the first hit
  1668. return dataPoint;
  1669. }
  1670. }
  1671. }
  1672. }
  1673. }
  1674. else {
  1675. // find the closest data point, using distance to the center of the point on 2d screen
  1676. for (i = 0; i < this.dataPoints.length; i++) {
  1677. dataPoint = this.dataPoints[i];
  1678. var point = dataPoint.screen;
  1679. if (point) {
  1680. var distX = Math.abs(x - point.x);
  1681. var distY = Math.abs(y - point.y);
  1682. var dist = Math.sqrt(distX * distX + distY * distY);
  1683. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  1684. closestDist = dist;
  1685. closestDataPoint = dataPoint;
  1686. }
  1687. }
  1688. }
  1689. }
  1690. return closestDataPoint;
  1691. };
  1692. /**
  1693. * Display a tooltip for given data point
  1694. * @param {Object} dataPoint
  1695. * @private
  1696. */
  1697. Graph3d.prototype._showTooltip = function (dataPoint) {
  1698. var content, line, dot;
  1699. if (!this.tooltip) {
  1700. content = document.createElement('div');
  1701. content.style.position = 'absolute';
  1702. content.style.padding = '10px';
  1703. content.style.border = '1px solid #4d4d4d';
  1704. content.style.color = '#1a1a1a';
  1705. content.style.background = 'rgba(255,255,255,0.7)';
  1706. content.style.borderRadius = '2px';
  1707. content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)';
  1708. line = document.createElement('div');
  1709. line.style.position = 'absolute';
  1710. line.style.height = '40px';
  1711. line.style.width = '0';
  1712. line.style.borderLeft = '1px solid #4d4d4d';
  1713. dot = document.createElement('div');
  1714. dot.style.position = 'absolute';
  1715. dot.style.height = '0';
  1716. dot.style.width = '0';
  1717. dot.style.border = '5px solid #4d4d4d';
  1718. dot.style.borderRadius = '5px';
  1719. this.tooltip = {
  1720. dataPoint: null,
  1721. dom: {
  1722. content: content,
  1723. line: line,
  1724. dot: dot
  1725. }
  1726. };
  1727. }
  1728. else {
  1729. content = this.tooltip.dom.content;
  1730. line = this.tooltip.dom.line;
  1731. dot = this.tooltip.dom.dot;
  1732. }
  1733. this._hideTooltip();
  1734. this.tooltip.dataPoint = dataPoint;
  1735. if (typeof this.showTooltip === 'function') {
  1736. content.innerHTML = this.showTooltip(dataPoint.point);
  1737. }
  1738. else {
  1739. content.innerHTML = '<table>' +
  1740. '<tr><td>' + this.xLabel + ':</td><td>' + dataPoint.point.x + '</td></tr>' +
  1741. '<tr><td>' + this.yLabel + ':</td><td>' + dataPoint.point.y + '</td></tr>' +
  1742. '<tr><td>' + this.zLabel + ':</td><td>' + dataPoint.point.z + '</td></tr>' +
  1743. '</table>';
  1744. }
  1745. content.style.left = '0';
  1746. content.style.top = '0';
  1747. this.frame.appendChild(content);
  1748. this.frame.appendChild(line);
  1749. this.frame.appendChild(dot);
  1750. // calculate sizes
  1751. var contentWidth = content.offsetWidth;
  1752. var contentHeight = content.offsetHeight;
  1753. var lineHeight = line.offsetHeight;
  1754. var dotWidth = dot.offsetWidth;
  1755. var dotHeight = dot.offsetHeight;
  1756. var left = dataPoint.screen.x - contentWidth / 2;
  1757. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  1758. line.style.left = dataPoint.screen.x + 'px';
  1759. line.style.top = (dataPoint.screen.y - lineHeight) + 'px';
  1760. content.style.left = left + 'px';
  1761. content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px';
  1762. dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px';
  1763. dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px';
  1764. };
  1765. /**
  1766. * Hide the tooltip when displayed
  1767. * @private
  1768. */
  1769. Graph3d.prototype._hideTooltip = function () {
  1770. if (this.tooltip) {
  1771. this.tooltip.dataPoint = null;
  1772. for (var prop in this.tooltip.dom) {
  1773. if (this.tooltip.dom.hasOwnProperty(prop)) {
  1774. var elem = this.tooltip.dom[prop];
  1775. if (elem && elem.parentNode) {
  1776. elem.parentNode.removeChild(elem);
  1777. }
  1778. }
  1779. }
  1780. }
  1781. };
  1782. /**--------------------------------------------------------------------------**/
  1783. /**
  1784. * Get the horizontal mouse position from a mouse event
  1785. * @param {Event} event
  1786. * @return {Number} mouse x
  1787. */
  1788. function getMouseX (event) {
  1789. if ('clientX' in event) return event.clientX;
  1790. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  1791. }
  1792. /**
  1793. * Get the vertical mouse position from a mouse event
  1794. * @param {Event} event
  1795. * @return {Number} mouse y
  1796. */
  1797. function getMouseY (event) {
  1798. if ('clientY' in event) return event.clientY;
  1799. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  1800. }
  1801. // -----------------------------------------------------------------------------
  1802. // Public methods for specific settings
  1803. // -----------------------------------------------------------------------------
  1804. /**
  1805. * Set the rotation and distance of the camera
  1806. * @param {Object} pos An object with the camera position. The object
  1807. * contains three parameters:
  1808. * - horizontal {Number}
  1809. * The horizontal rotation, between 0 and 2*PI.
  1810. * Optional, can be left undefined.
  1811. * - vertical {Number}
  1812. * The vertical rotation, between 0 and 0.5*PI
  1813. * if vertical=0.5*PI, the graph is shown from the
  1814. * top. Optional, can be left undefined.
  1815. * - distance {Number}
  1816. * The (normalized) distance of the camera to the
  1817. * center of the graph, a value between 0.71 and 5.0.
  1818. * Optional, can be left undefined.
  1819. */
  1820. Graph3d.prototype.setCameraPosition = function(pos) {
  1821. Settings.setCameraPosition(pos, this);
  1822. this.redraw();
  1823. };
  1824. // -----------------------------------------------------------------------------
  1825. // End public methods for specific settings
  1826. // -----------------------------------------------------------------------------
  1827. module.exports = Graph3d;