How to reduce the font of the text in the canvas, so that it does not go beyond the canvas? using measureText and a while , in which the font is reduced, while it is wider than the canvas , the font goes into minuses and the width of the text is determined incorrectly. how to fix?

 var forFont = 30; var topMeasure = context.measureText(top).width; console.log(topMeasure); while(topMeasure > canvas.width){ forFont--; } context.font = forFont + "pt Impact"; 

    1 answer 1

    Yes, a very simple solution.

    • The width of the canvas is more convenient to take in a constant.
    • Next, we take 1 more font size, because in order to write less code, it is easier to implement through do {} while();

    And that's what we did.

     var CANVAS_WIDTH = canvas.width; var txt = 'lorem impsum dolor ...'; var fontSize = 31; do { fontSize--; ctx.font = fontSize + 'px Arial'; } while (ctx.measureText(txt).width > CANVAS_WIDTH);