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.

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