node.jscanvasdiscord.jsnode-canvas

Canvas incorrect measureText()


I am making a Discord bot and trying to display someone's level, I would like it to basically say "LEVEL 1" for example, but the distance between the word level and the actual level would change depending on the level they are on. So I am trying to offset the word a little, but when I use measureText(), it displays incorrectly. Code:

    const levelNumber = '1';
    const levelText = 'LEVEL';

    ctx.font = '48px Shapirit';
    ctx.fillStyle = '#FF1700';
    ctx.textAlign = 'right';
    ctx.fillText(levelNumber, 880, 96.8);

    ctx.font = '22px Shapirit';
    ctx.fillStyle = '#FF1700';
    ctx.textAlign = 'right';
    ctx.fillText(levelText, 880 - ctx.measureText(levelNumber).width - 20, 96.8);

Here is the current output: output 1 output 2


Solution

  • Yes @Jay is right. You have to measureText with the right font, if not you get the wrong results.

    See sample below

    function drawLevel(x, y, txt, num, style) {
      ctx.font = '48px Shapirit';
      ctx.fillStyle = style;
      ctx.textAlign = 'right';
      ctx.fillText(num, x, y);
      w = ctx.measureText(num).width
    
      ctx.font = '22px Shapirit';
      ctx.fillStyle = style;
      ctx.textAlign = 'right';
      ctx.fillText(txt, x - w - 20, y);
    }
    
    
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    
    drawLevel(200, 40, 'LEVEL', '999', '#FF1700');
    drawLevel(200, 80, 'LEVEL', '11', '#0000FF');
    drawLevel(200, 120, 'LEVEL', '1', '#00FF00');
    <canvas id="canvas">