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.

2345 lines
73 KiB

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