Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function drawText(ctx, width, height, text) {
- const fontSize = 30;
- const textMargin = 5;
- ctx.font = `${fontSize}px arial`;
- ctx.textAlign = 'center';
- ctx.textBaseline = 'top';
- ctx.fillStyle = '#ffffff';
- const textLines = wrappedLines(ctx, text, width * 0.9);
- const linesCount = textLines.length;
- const textHeight = (linesCount * fontSize) + ((linesCount - 1) * textMargin);
- const startY = (height - textHeight) / 2;
- textLines.forEach((line, i) => {
- const lineY = startY + i * (fontSize + textMargin);
- ctx.fillText(line, width / 2, lineY);
- });
- }
- function wrappedLines(ctx, text, maxWidth) {
- const words = text.split(" ");
- const lines = [];
- let currentLine = words[0];
- for (let i = 1; i < words.length; i++) {
- let word = words[i];
- let width = ctx.measureText(currentLine + " " + word).width;
- if (width < maxWidth) {
- currentLine += " " + word;
- } else {
- lines.push(currentLine);
- currentLine = word;
- }
- }
- lines.push(currentLine);
- return lines;
- }
- function drawOverlay(ctx, width, height) {
- ctx.fillStyle = "rgba(0, 0, 0, 0.4)";
- ctx.fillRect(0, 0, width, height);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement