JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvasOne" width="500" height="500">
Your browser does not support HTML5 Canvas.
</canvas>
nlnknl
JavaScript
var x0 = 100;
var y0 = 100;
var maxWidth = 50;
var lineHeight = 20;
theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
var text = 'word';
context.font = '16pt Calibri';
context.fillStyle = '#333';
var p0 = {x:x0,y:y0};
var word = {x:p0.x, y:p0.y, velocityx: 0, velocityy:0};
var lastTime = new Date().getTime();
wrapText(context, text, p0.x, p0.y, maxWidth, lineHeight);
/* THIS SHOULD CLEAR YOUR TEXT 'word' */
var metrics = context.measureText('word');
context.clearRect(
p0.x,
p0.y,
metrics.width > maxWidth ? metrics.width : maxWidth,
- text.split(' ').length * lineHeight);
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var words = text.split(' ');
var line = '';
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
context.fillText(line, x, y);
}