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.

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