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.

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