Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. function drawText(ctx, width, height, text) {
  2. const fontSize = 30;
  3. const textMargin = 5;
  4.  
  5. ctx.font = `${fontSize}px arial`;
  6. ctx.textAlign = 'center';
  7. ctx.textBaseline = 'top';
  8. ctx.fillStyle = '#ffffff';
  9.  
  10. const textLines = wrappedLines(ctx, text, width * 0.9);
  11. const linesCount = textLines.length;
  12. const textHeight = (linesCount * fontSize) + ((linesCount - 1) * textMargin);
  13. const startY = (height - textHeight) / 2;
  14.  
  15. textLines.forEach((line, i) => {
  16. const lineY = startY + i * (fontSize + textMargin);
  17. ctx.fillText(line, width / 2, lineY);
  18. });
  19. }
  20.  
  21. function wrappedLines(ctx, text, maxWidth) {
  22. const words = text.split(" ");
  23. const lines = [];
  24. let currentLine = words[0];
  25.  
  26. for (let i = 1; i < words.length; i++) {
  27. let word = words[i];
  28. let width = ctx.measureText(currentLine + " " + word).width;
  29. if (width < maxWidth) {
  30. currentLine += " " + word;
  31. } else {
  32. lines.push(currentLine);
  33. currentLine = word;
  34. }
  35. }
  36.  
  37. lines.push(currentLine);
  38. return lines;
  39. }
  40.  
  41. function drawOverlay(ctx, width, height) {
  42. ctx.fillStyle = "rgba(0, 0, 0, 0.4)";
  43. ctx.fillRect(0, 0, width, height);
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement