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.

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