diff --git a/www/index.html b/www/index.html index ce6d81c..ad0fb2e 100644 --- a/www/index.html +++ b/www/index.html @@ -91,6 +91,19 @@ Dump Traffic --> + Text font + + Serif + Sans-serif + Monospace + Cursive + + + + Text size: + + px + 🌎 Accessibility diff --git a/www/main.js b/www/main.js index bdff35b..c589b96 100644 --- a/www/main.js +++ b/www/main.js @@ -439,31 +439,46 @@ class CanvasController { } } insertText() { - let text = prompt("Enter text"); - let lines = []; + + const textSize = parseInt(document.getElementById("text-size").value); + const textFont = document.getElementById("text-font").value; + const yStep = textSize; + + const ctx = this.canvas.getContext("2d"); + ctx.font = textSize + "px " + textFont; + // const textWidth = ctx.measureText(textSize); + const maxWidth = this.canvas.width - 10; + + let text = prompt("Enter text"); + if (text == null) { return; } + // Use Word Wrap to split the text over multiple lines + let lines = []; + const getMaxCharsPerLine = (text, ctx) => { + let textWidth = ctx.measureText(text).width; + let textIndex = maxWidth / textWidth; + + if (textIndex > 1) { return text.length} + return Math.floor(textIndex * text.length); + } const wrapText = (text, maxLength) => { let splitPos = maxLength - 1; while (text[splitPos] != " " && splitPos > 0) { splitPos--; } if (splitPos == 0) { splitPos = maxLength; } - return [text.slice(0, splitPos), text.slice(splitPos, text.length)]; + return [text.slice(0, splitPos).trim(), text.slice(splitPos, text.length).trim()]; } - const maxLength = 33; - while (text.length > maxLength) { + while (ctx.measureText(text).width > maxWidth) { let line; - [line, text] = wrapText(text, maxLength); + [line, text] = wrapText(text, getMaxCharsPerLine(text, ctx)); lines.push(line); } lines.push(text) - let ctx = this.canvas.getContext("2d"); - ctx.font = "20px Sans-Serif"; - const yStep = 20; let yPos = yStep; for (let line of lines) { ctx.fillText(line, 0, yPos);