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.

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