Graph.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import {Object2D} from "../Object2D.js";
  2. import {Vector2} from "../math/Vector2.js";
  3. import {Box2} from "../math/Box2.js";
  4. /**
  5. * Graph object is used to draw simple graph data into the canvas.
  6. *
  7. * Graph data is composed of X, Y values.
  8. *
  9. * @class
  10. * @extends {Object2D}
  11. */
  12. function Graph()
  13. {
  14. Object2D.call(this);
  15. /**
  16. * Graph object containing the size of the object.
  17. */
  18. this.box = new Box2(new Vector2(-50, -35), new Vector2(50, 35));
  19. /**
  20. * Color of the box border line.
  21. */
  22. this.strokeStyle = "rgb(0, 153, 255)";
  23. /**
  24. * Line width.
  25. */
  26. this.lineWidth = 1;
  27. /**
  28. * Background color of the box.
  29. */
  30. this.fillStyle = "rgba(0, 153, 255, 0.3)";
  31. /**
  32. * Minimum value of the graph.
  33. */
  34. this.min = 0;
  35. /**
  36. * Maximum value of the graph.
  37. */
  38. this.max = 10;
  39. /**
  40. * Data to be presented in the graph.
  41. *
  42. * The array should store numeric values.
  43. */
  44. this.data = [];
  45. }
  46. Graph.prototype = Object.create(Object2D.prototype);
  47. Graph.prototype.isInside = function(point)
  48. {
  49. return this.box.containsPoint(point);
  50. };
  51. Graph.prototype.draw = function(context, viewport, canvas)
  52. {
  53. if(this.data.length === 0)
  54. {
  55. return;
  56. }
  57. var width = this.box.max.x - this.box.min.x;
  58. var height = this.box.max.y - this.box.min.y;
  59. context.lineWidth = this.lineWidth;
  60. context.strokeStyle = this.strokeStyle;
  61. context.beginPath();
  62. var step = width / (this.data.length - 1);
  63. var gamma = this.max - this.min;
  64. context.moveTo(this.box.min.x, this.box.max.y - ((this.data[0] - this.min) / gamma) * height);
  65. for(var i = 1, s = step; i < this.data.length; s += step, i++)
  66. {
  67. context.lineTo(this.box.min.x + s, this.box.max.y - ((this.data[i] - this.min) / gamma) * height);
  68. }
  69. context.stroke();
  70. if(this.fillStyle !== null)
  71. {
  72. context.fillStyle = this.fillStyle;
  73. context.lineTo(this.box.max.x, this.box.max.y);
  74. context.lineTo(this.box.min.x, this.box.max.y);
  75. context.fill();
  76. }
  77. };
  78. export {Graph};