Path.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import {Object2D} from "../Object2D.js";
  2. import {ColorStyle} from "./style/ColorStyle";
  3. import {Style} from "./style/Style";
  4. /**
  5. * Path object can be used to draw paths build from commands into the canvas.
  6. *
  7. * These paths can be also obtained from SVG files as a SVG command list.
  8. *
  9. * @class
  10. * @extends {Object2D}
  11. */
  12. function Path(path)
  13. {
  14. Object2D.call(this);
  15. /**
  16. * Path2D object containing the commands to draw the shape into the canvas.
  17. *
  18. * Check https://developer.mozilla.org/en-US/docs/Web/API/Path2D/Path2D for more details.
  19. *
  20. * @type {Path2D}
  21. */
  22. this.path = path !== undefined ? path : new Path2D("M10 10 h 80 v 80 h -80 Z");
  23. /**
  24. * Style of the object border line.
  25. *
  26. * If set null it is ignored.
  27. *
  28. * @type {Style}
  29. */
  30. this.strokeStyle = new ColorStyle("#000000");
  31. /**
  32. * Line width, only used if a valid strokeStyle is defined.
  33. *
  34. * @type {number}
  35. */
  36. this.lineWidth = 1;
  37. /**
  38. * Background color of the path.
  39. *
  40. * If set null it is ignored.
  41. *
  42. * @param {Style}
  43. */
  44. this.fillStyle = new ColorStyle("#FFFFFF");
  45. }
  46. Path.prototype = Object.create(Object2D.prototype);
  47. Path.prototype.constructor = Path;
  48. Path.prototype.type = "Path";
  49. Object2D.register(Path, "Path");
  50. Path.prototype.draw = function(context)
  51. {
  52. if(this.fillStyle !== null)
  53. {
  54. context.fillStyle = this.fillStyle.get(context);
  55. context.fill(this.path);
  56. }
  57. if(this.strokeStyle !== null)
  58. {
  59. context.lineWidth = this.lineWidth;
  60. context.strokeStyle = this.strokeStyle.get(context);
  61. context.stroke(this.path);
  62. }
  63. };
  64. Path.prototype.serialize = function(recursive)
  65. {
  66. var data = Object2D.prototype.serialize.call(this, recursive);
  67. data.strokeStyle = this.strokeStyle !== null ? this.strokeStyle.serialize() : null;
  68. data.lineWidth = this.lineWidth;
  69. data.fillStyle = this.fillStyle !== null ? this.fillStyle.serialize() : null;
  70. return data;
  71. };
  72. Path.prototype.parse = function(data, root)
  73. {
  74. Object2D.prototype.parse.call(this, data, root);
  75. this.strokeStyle = data.strokeStyle !== null ? Style.parse(data.strokeStyle) : null;
  76. this.lineWidth = data.lineWidth;
  77. this.fillStyle = data.fillStyle !== null ? Style.parse(data.fillStyle) : null;
  78. };
  79. export {Path};