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.

2349 lines
73 KiB

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