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.

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