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.

2344 lines
73 KiB

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