Graph.js 2.0 KB

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