js canvas - Compute text width with specific text-weight

I'm currently using the following code to calculate text width:

function measureWordSize(word, font) {
    var canvas = measureWordSize.canvas || (measureWordSize.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(word);
    return metrics.width;

Which works fine, but the font property has to be a string formatted like so: [italic] [bold] <font-size> <font-family>.

I want to calculate the text's width with a certain text-weight, and setting font to 700px <font-size> <font-family> doesn't work. MDN doesn't say anything about a numeric text-weight.

How do I calculate text width for an element with a numeric text-weight?

1 answer

  • answered 2017-11-13 00:59 Kaiido

    context.font accepts the same format as CSS font shorthand property.

    Taken from MDN

    /* size | family */
    font: 2em "Open Sans", sans-serif;

    /* style | size | family */
    font: italic 2em "Open Sans", sans-serif;

    /* style | variant | weight | size/line-height | family */
    font: italic small-caps bolder 16px/3 cursive;

    /* style | variant | weight | stretch | size/line-height | family */
    font: italic small-caps bolder condensed 16px/3 cursive;

    So you can also set the font-weight as numeric scale, just like with CSS:

    const ctx = canvas.getContext('2d');
    const str = "I'm bold";
    // set the font as numeric-font-weight | font-size | font-name
    ctx.font = '700 16px sans-serif';
    console.log('bold:', ctx.measureText(str).width);
    ctx.fillText(str, 0, 20)
    // reset to normal font-weight
    ctx.font = '400 16px sans-serif';
    console.log('medium:', ctx.measureText(str).width);
    <canvas id="canvas"></canvas>