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.

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