MultiLineText.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. * Text baseline defines the vertical position of the text relative to the imaginary line Y position.
  15. *
  16. * @type {string}
  17. */
  18. this.textBaseline = "middle";
  19. /**
  20. * Maximum width of the text content. After text reaches the max width a line break is placed.
  21. *
  22. * @type {number}
  23. */
  24. this.maxWidth = 100;
  25. /**
  26. * Height of each line of text, can be smaller or larger than the actual font size.
  27. *
  28. * Can be set to null to be ignored.
  29. *
  30. * @type {number}
  31. */
  32. this.lineHeight = 100;
  33. }
  34. MultiLineText.prototype = Object.create(Text.prototype);
  35. MultiLineText.prototype.draw = function(context, viewport, canvas)
  36. {
  37. context.font = this.font;
  38. context.textAlign = this.textAlign;
  39. context.textBaseline = this.textBaseline;
  40. context.font = font;
  41. var lineHeight = this.lineHeight || Number.parseFloat(font);
  42. var lines = text.split("\n");
  43. var offsetY = 0;
  44. // Iterate trough all lines (breakpoints)
  45. for(var i = 0; i < lines.length; i++)
  46. {
  47. var line = lines[i];
  48. var size = context.measureText(line);
  49. var sublines = [];
  50. // Split into multiple sub-lines
  51. if(size.width > this.maxWidth)
  52. {
  53. while(line.length > 0)
  54. {
  55. var subline = "";
  56. var subsize = context.measureText(subline + line[0]);
  57. while(subsize.width < this.maxWidth && line.length > 0)
  58. {
  59. subline += line[0];
  60. line = line.substr(1);
  61. subsize = context.measureText(subline + line[0]);
  62. }
  63. sublines.push(subline);
  64. }
  65. }
  66. // Fits into a single line
  67. else
  68. {
  69. sublines = [line];
  70. }
  71. for(var j = 0; j < sublines.length; j++)
  72. {
  73. if(this.fillStyle !== null)
  74. {
  75. context.fillStyle = this.fillStyle;
  76. context.fillText(sublines[j], x, y + offsetY);
  77. }
  78. if(this.strokeStyle !== null)
  79. {
  80. context.strokeStyle = this.strokeStyle;
  81. context.strokeText(sublines[j], x, y + offsetY);
  82. }
  83. offsetY += lineHeight;
  84. }
  85. }
  86. };
  87. export {MultiLineText};