Search code examples
texthtml5-canvas

How to draw text on html-5 canvas given bottom right x,y


Does anyone know how to draw text on a html-5 canvas given its bottom right x,y coordinates? The .fillText("text", x, y) draws the text's top left corner at x,y I need it to draw the bottom right corner at x,y. If anyone knows the answer that would be very helpful.


Solution

  • get the width by using the measure text width

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

    and (if you require it) you can get the approximate height by using your font size

    ctx.font = "25px serif";
    var height = parseInt(ctx.font.substring(0, 2)); // gets the font size
    

    and since it renders bottom left, you just need to minus it

    ctx.fillText("text", x - width, y);