MultiLineText.js 2.0 KB

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