Define how many words do you have, after that draw rect
based on length of words.
Example
const words = text.split(' ');
const incrementFactor = 4; // it adds 4 pixels to rect for each line
const paragraphCount = words.length // Define the paragraph count
ctx.fillRect(20,20,250,paragraphCount*incrementFactor);
ctx.fillStyle = 'black';
drawWords(ctx, text, x, y, maxWidth, lineHeight,rectHeight,words)
You need to redraw canvas in each update.
I suggest first define all elements to be drawn and after that draw it. Canvas does not have real-time updates, you need to redraw in each update.
working code https://jsfiddle.net/vf8gvq7m/91/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…