JSFiddle - React, Tailwind, and code Playground

HTML

<textarea id="textArea"></textarea><br>
<button id="myButton">Show Canvas</button><br>
<canvas id="myCanvas"></canvas>

JavaScript

$('#myButton').click(function(){
 showCanvas();   
});


function showCanvas(){

var elem = document.getElementById('myCanvas');
    
    var wd = 200;
    var ht = 110;
 
    ctx = elem.getContext('2d');
    ctx.canvas.width = wd;
    ctx.canvas.height = ht;
    ctx.fillStyle = '#CCC'; // text area BG color
    ctx.fillRect(0,0,wd,ht);
    
// Image placeholder    
 ctx.fillStyle = '#f00'; 
ctx.fillRect(0,0,200,90);
// end Image placeholder

var str = $('#textArea').val();
var maxWidth = 190;
 var lineHeight = 14;
 var x = 100;
 var y = 104;  
 var lineCount = 1;
    
 var splittext = $.map(str.split(" "), function (t) { // Split words > than 20 words length
return t.match(/[\s\S]{1,20}/g) || [];
}).join(" ");
    
ctx.font = 'normal normal 14px monospace';
ctx.textAlign = 'center';
ctx.fillStyle = '#000';

wrapText(ctx, splittext, x, y, maxWidth, lineHeight);

function wrapText(context, text, x, y, maxWidth, fontSize, fontFace){
var words = text.split(' ');
var line = '';
var lineHeight = fontSize;

context.font=fontSize+" "+fontFace;

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) {
context.fillText(line, x, y);
line = words[n] + ' ';
 y += lineHeight;
if(++lineCount>1){
 
    // TODO: The canvas is resizing, but it only displays the last line of text since a wipe is performed before resize. How can I redraw last canvas state?
    
elem.height = elem.height+(lineHeight+lineCount); // Resize amount
ctx.font = 'normal normal 14px monospace';
ctx.textAlign = 'center';
ctx.fillStyle = '#000'; 
    
    
    // return(y);


}   
}
else {
line = testLine;
}
}
context.fillText(line, x, y);
return(y);
}
    
}