开发者

HTML5 canvas: Draw rectangle around text?

开发者 https://www.devze.com 2023-01-23 01:42 出处:网络
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 le

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 < n开发者_如何学Pythonum_people; i++) {
    var pos = get_position(i, num_people);
    ctx.fillText(names[i], pos.x, pos.y);
}


You can get the size of the drawn text with measureText().


Useful links for canvas text:

  • https://developer.mozilla.org/en/drawing_text_using_a_canvas (in particular the part on textBaseline and the nice diagram)
  • How to add a border on HTML5 Canvas' Text?
0

精彩评论

暂无评论...
验证码 换一张
取 消