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.

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