JSFiddle - React, Tailwind, and code Playground

HTML

<canvas id="canvas1" width="500" height="500"></canvas>

JavaScript

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

function drawSomeText(x, y, text, maxWidth) {
    //metric will receive the measures of the text
    var metric = ctx.measureText(text); 
    console.log(metric.width);
    
    ctx.save(); // this will "save" the normal canvas to return to
    if(maxWidth != null && metric.width > maxWidth) {
        // These two methods will change EVERYTHING
        // drawn on the canvas from this point forward
        // Since we only want them to apply to this one fillText,
        // we use save and restore before and after
        
        // We want to find the center of the text (or whatever point you want) and rotate about it
        var tx = x + (metric.width/2);
        var ty = y + 5;
        
        // Translate to near the center to rotate about the center
        ctx.translate(tx,ty);
        // Then rotate...
        ctx.rotate(Math.PI / 2);
        // Then translate back to draw in the right place!
        ctx.translate(-tx,-ty);
    }
    ctx.fillText(text, x, y);
    ctx.restore(); // This will un-translate and un-rotate the canvas
}

drawSomeText(50,50,'lalalala', 10); // this one will rotate
drawSomeText(150,50,'One two three', 200); // this one wont!
drawSomeText(250,50,'Baby blue', 20); // this one will again!