JSFiddle - React, Tailwind, and code Playground
by rlemon
HTML
<canvas id="canvas" height="200" width="200"></canvas>
<input type="text" id="sentence" value="" placeholder="your text here" />
<input type="number" id="font_size" min="10" max="96" value="22" />
JavaScript
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
font_input = document.getElementById('font_size');
document.getElementById('sentence').onkeyup = draw;
font_input.onchange = draw;
ctx.textAlign = "center"; // required for centered text in demo
function draw() {
var lines = fragmentText(this.value, canvas.width * 0.9),
font_size = font_input.value,
strike_width = font_size / 9.6;
ctx.font = "Bold " + font_size + "px Arial";
ctx.strokeStyle = "black";
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
lines.forEach(function (line, i) {
var width = ctx.measureText(line).width,
x = canvas.width / 2 - width / 2,
y = ((i + 1) * font_size)-(font_size / 3.33);
ctx.fillText(line, canvas.width / 2, (i + 1) * font_size);
ctx.beginPath();
ctx.lineWidth = font_size / 9.4;
ctx.moveTo(x, y);
ctx.lineTo(x + width, y);
ctx.stroke();
});
ctx.restore();
}
function fragmentText(text, maxWidth) {
var words = text.split(' '),
lines = [],
line = "";
if (ctx.measureText(text).width < maxWidth) {
return [text];
}
while (words.length > 0) {
while (ctx.measureText(words[0]).width >= maxWidth) {
var tmp = words[0];
words[0] = tmp.slice(0, -1);
if (words.length > 1) {
words[1] = tmp.slice(-1) + words[1];
} else {
words.push(tmp.slice(-1));
}
}
if (ctx.measureText(line + words[0]).width < maxWidth) {
line += words.shift() + " ";
} else {
lines.push(line);
line = "";
}
if (words.length === 0) {
lines.push(line);
}
}
return lines;
}