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.

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