var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'); document.getElementById('sentence').onkeyup = draw; ctx.textAlign = "center"; // required for centered text in demo function draw() { var lines = fragmentText(this.value, canvas.width * 0.9), font_size = 22; // px ctx.font = "Bold " + font_size + "px Arial"; ctx.save(); ctx.clearRect(0, 0, canvas.width, canvas.height); lines.forEach(function(line, i) { ctx.fillText(line, canvas.width / 2, (i + 1) * font_size); }); 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; }
<canvas id="canvas" height="200" width="200"></canvas> <input type="text" id="sentence" value="" placeholder="your text here" />