0

Hello all I've tried relentlessly to write a script that will check the width of a string and if it is greater than a certain amount, lower the font size and draw it again. Except this is not working. Once I initially draw the text, it never updates to the correct font size. It just stays what it was originally and never gets any smaller throwing the script into an endless loop. Here is my code:

var nFontSize = 25;

var draw_name = function(text) {
    var c=document.getElementById("badgeCanvas");
    var ctx=c.getContext("2d");
    ctx.font="nFontSize OpenSansBold";
    ctx.fillStyle = "#000000";
    ctx.fillText(text,80,25);
    var metrics = ctx.measureText(text);
    var width = metrics.width;

    while (width > 200) {
        nFontSize--;
        ctx.font="nFontSize OpenSansBold";
        ctx.fillText(text,80,25);
        metrics = ctx.measureText(text);
        width = metrics.width;
    }

    ctx.font="nFontSize OpenSansBold";
    ctx.fillStyle = "#000000";
    ctx.fillText(text,80,25);

1 Answer 1

1

"nFontSize OpenSansBold" is not a valid font. Try

ctx.font= nFontSize + "px OpenSansBold";

Also, you don't have to render it to measure the text so remove the ctx.fillText(text,80,25); before your while loop and inside your while loop. Otherwise, it will look ugly.

var nFontSize = 25;

var draw_name = function(text) {
    var c=document.getElementById("badgeCanvas");
    var ctx=c.getContext("2d");
    ctx.font= nFontSize + "px OpenSansBold";
    ctx.fillStyle = "#000000";

    var metrics = ctx.measureText(text);
    var width = metrics.width;

    while (width > 200) {
        nFontSize--;
        ctx.font= nFontSize + "px OpenSansBold";

        metrics = ctx.measureText(text);
        width = metrics.width;
    }

    ctx.font= nFontSize + "px OpenSansBold";
    ctx.fillStyle = "#000000";
    ctx.fillText(text,80,25);
Sign up to request clarification or add additional context in comments.

2 Comments

It's a font I imported in the css, would this answer still apply?
Sorry, it's not the font, it's the string you are using to set the ctx.font property. "nFontsize OpenSansBold" is a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.