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.

2490 lines
71 KiB

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