简体   繁体   中英

HTML5 canvas: Draw rectangle around text?

I want to be able to draw a fitted rectangle around text labels (person's full name). The margin isn't terribly important, but I can't just draw fixed-sized rectangles because the labels vary in lengths. How do I do this?

Here's the code that draws the text labels:

var ctx = document.getElementById('map').getContext('2d');
for (i=0; i < num_people; i++) {
    var pos = get_position(i, num_people);
    ctx.fillText(names[i], pos.x, pos.y);
}

您可以使用measureText()获得绘制文本的大小。

Useful links for canvas text:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM