JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id='i' width=500 height=5000></canvas>
<script>
function d(){
var c=document.getElementById("i");
var ctx=c.getContext("2d");
ctx.font="15px Arial";
var maxWidth = 300;
var lineHeight = 25;
var x = (c.width - maxWidth) / 2;
var y = 60;
str = "<canvas id='i' width=5000 height=500></canvas><script>"+d+"d();"+wrapText+"<\/script>";
wrapText(ctx, str, x, y, maxWidth, lineHeight);
}
d();
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.lineWidth = 1;
context.strokeStyle = 'blue';
context.strokeText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
context.lineWidth = 1;
context.strokeStyle = 'blue';
context.strokeText(line, x, y);
}
</script>