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.

2343 lines
69 KiB

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