SHARE
TWEET

Untitled

a guest Apr 20th, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top