Line.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import {Object2D} from "../Object2D.js";
  2. import {Vector2} from "../math/Vector2.js";
  3. /**
  4. * Line object draw a line from one point to another without any kind of interpolation.
  5. *
  6. * For drawing lines with interpolation check {BezierCurve}
  7. *
  8. * @class
  9. * @extends {Object2D}
  10. */
  11. function Line()
  12. {
  13. Object2D.call(this);
  14. /**
  15. * Initial point of the line.
  16. *
  17. * Can be equal to the position object of another object. Making it automatically follow that object.
  18. *
  19. * @type {Vector2}
  20. */
  21. this.from = new Vector2();
  22. /**
  23. * Final point of the line.
  24. *
  25. * Can be equal to the position object of another object. Making it automatically follow that object.
  26. *
  27. * @type {Vector2}
  28. */
  29. this.to = new Vector2();
  30. /**
  31. * Dash line pattern to be used, if empty draws a solid line.
  32. *
  33. * Dash pattern is defined as the size of dashes as pairs of space with no line and with line.
  34. *
  35. * E.g if the dash pattern is [1, 2] we get 1 point with line, 2 without line repeat infinitelly.
  36. *
  37. * @type {number[]}
  38. */
  39. this.dashPattern = [5, 5];
  40. /**
  41. * Style of the object line.
  42. *
  43. * @type {string}
  44. */
  45. this.strokeStyle = "#000000";
  46. /**
  47. * Line width of the line.
  48. *
  49. * @type {number}
  50. */
  51. this.lineWidth = 1;
  52. }
  53. Line.prototype = Object.create(Object2D.prototype);
  54. Line.prototype.constructor = Line;
  55. Line.prototype.type = "Line";
  56. Object2D.register(Line, "Line");
  57. Line.prototype.style = function(context, viewport, canvas)
  58. {
  59. context.lineWidth = this.lineWidth;
  60. context.strokeStyle = this.strokeStyle;
  61. context.setLineDash(this.dashPattern);
  62. };
  63. Line.prototype.draw = function(context, viewport, canvas)
  64. {
  65. context.beginPath();
  66. context.moveTo(this.from.x, this.from.y);
  67. context.lineTo(this.to.x, this.to.y);
  68. context.stroke();
  69. };
  70. Line.prototype.serialize = function(recursive)
  71. {
  72. var data = Object2D.prototype.serialize.call(this, recursive);
  73. data.from = this.from.toArray();
  74. data.to = this.to.toArray();
  75. data.dashPattern = this.dashPattern;
  76. data.strokeStyle = this.strokeStyle;
  77. data.lineWidth = this.lineWidth;
  78. return data;
  79. };
  80. Line.prototype.parse = function(data)
  81. {
  82. Object2D.prototype.parse.call(this, data);
  83. this.to.fromArray(data.to);
  84. this.from.fromArray(data.from);
  85. this.dashPattern = data.dashPattern;
  86. this.strokeStyle = data.strokeStyle;
  87. this.lineWidth = data.lineWidth;
  88. };
  89. export {Line};