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.

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