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.

2321 lines
66 KiB

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