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.

2409 lines
72 KiB

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