Search code examples
htmlcanvas

How to get the bounding box of a text using html5 canvas?


I would like to get some text's bounding box.


Solution

  • I found the answer before I submited the question:

    http://mudcu.be/journal/2011/01/html5-typographic-metrics/#bboxUnicode http://www.w3schools.com/tags/canvas_measuretext.asp

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

    I used line height for text_height.

    This gives not exact bounding box, but it is fast and usable before text rendering.