Text.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import {Object2D} from "../Object2D.js";
  2. /**
  3. * Text element, used to draw single line text into the canvas.
  4. *
  5. * For multi line text with support for line break check {MultiLineText} object.
  6. *
  7. * @class
  8. * @extends {Object2D}
  9. */
  10. function Text()
  11. {
  12. Object2D.call(this);
  13. /**
  14. * Text value displayed by this element.
  15. *
  16. * @type {string}
  17. */
  18. this.text = "";
  19. /**
  20. * Font of the text.
  21. *
  22. * @type {string}
  23. */
  24. this.font = "16px Arial";
  25. /**
  26. * Style of the object border line. If set null it is ignored.
  27. *
  28. * @type {string}
  29. */
  30. this.strokeStyle = null;
  31. /**
  32. * Line width, only used if a valid strokeStyle is defined.
  33. *
  34. * @type {number}
  35. */
  36. this.lineWidth = 1;
  37. /**
  38. * CSS background color of the box. If set null it is ignored.
  39. *
  40. * @type {string}
  41. */
  42. this.fillStyle = "#000000";
  43. /**
  44. * Text align property. Same values as used for canvas text applies
  45. *
  46. * Check documentation at https://developer.mozilla.org/en-US/docs/Web/CSS/text-align for mode details about this property.
  47. *
  48. * @type {string}
  49. */
  50. this.textAlign = "center";
  51. /**
  52. * Text baseline defines the vertical position of the text relative to the imaginary line Y position. Same values as used for canvas text applies
  53. *
  54. * Check documentation at https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textBaseline for mode details about this property.
  55. *
  56. * @type {string}
  57. */
  58. this.textBaseline = "middle";
  59. }
  60. Text.prototype = Object.create(Object2D.prototype);
  61. Text.prototype.draw = function(context, viewport, canvas)
  62. {
  63. context.font = this.font;
  64. context.textAlign = this.textAlign;
  65. context.textBaseline = this.textBaseline ;
  66. if(this.fillStyle !== null)
  67. {
  68. context.fillStyle = this.fillStyle;
  69. context.fillText(this.text, 0, 0);
  70. }
  71. if(this.strokeStyle !== null)
  72. {
  73. context.strokeStyle = this.strokeStyle;
  74. context.strokeText(this.text, 0, 0);
  75. }
  76. };
  77. export {Text};