MultiLineText.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import {Text} from "./Text.js";
  2. import {Line} from "./Line";
  3. /**
  4. * Multiple line text drawing directly into the canvas.
  5. *
  6. * Has support for basic text indent and alignment.
  7. *
  8. * @class
  9. * @extends {Text}
  10. */
  11. function MultiLineText()
  12. {
  13. Text.call(this);
  14. /**
  15. * Maximum width of the text content. After text reaches the max width a line break is placed.
  16. *
  17. * Can be set to null to be ignored.
  18. *
  19. * @type {number}
  20. */
  21. this.maxWidth = null;
  22. /**
  23. * Height of each line of text, can be smaller or larger than the actual font size.
  24. *
  25. * Can be set to null to be ignored.
  26. *
  27. * @type {number}
  28. */
  29. this.lineHeight = null;
  30. }
  31. MultiLineText.prototype = Object.create(Text.prototype);
  32. MultiLineText.prototype.constructor = MultiLineText;
  33. MultiLineText.prototype.draw = function(context, viewport, canvas)
  34. {
  35. context.font = this.font;
  36. context.textAlign = this.textAlign;
  37. context.textBaseline = this.textBaseline;
  38. var lineHeight = this.lineHeight || Number.parseFloat(this.font);
  39. var lines = this.text.split("\n");
  40. var offsetY = 0;
  41. // Iterate trough all lines (breakpoints)
  42. for(var i = 0; i < lines.length; i++)
  43. {
  44. var line = lines[i];
  45. var size = context.measureText(line);
  46. var sublines = [];
  47. // Split into multiple sub-lines
  48. if(this.maxWidth !== null && size.width > this.maxWidth)
  49. {
  50. while(line.length > 0)
  51. {
  52. var subline = "";
  53. var subsize = context.measureText(subline + line[0]);
  54. while(subsize.width < this.maxWidth && line.length > 0)
  55. {
  56. subline += line[0];
  57. line = line.substr(1);
  58. subsize = context.measureText(subline + line[0]);
  59. }
  60. sublines.push(subline);
  61. }
  62. }
  63. // Fits into a single line
  64. else
  65. {
  66. sublines = [line];
  67. }
  68. for(var j = 0; j < sublines.length; j++)
  69. {
  70. if(this.fillStyle !== null)
  71. {
  72. context.fillStyle = this.fillStyle;
  73. context.fillText(sublines[j], this.position.x, this.position.y + offsetY);
  74. }
  75. if(this.strokeStyle !== null)
  76. {
  77. context.strokeStyle = this.strokeStyle;
  78. context.strokeText(sublines[j], this.position.x, this.position.y + offsetY);
  79. }
  80. offsetY += lineHeight;
  81. }
  82. }
  83. };
  84. export {MultiLineText};