我知道我读过一些关于 Canvas 中的上升和字体高度的内容,但我根本不明白。
首先,为什么文本是从右到上绘制的,而不是像矩形那样从右到下绘制的。我在文档中找不到任何地方。然后,如果我想在字母周围绘制一个矩形,尤其是低于基线的“y”或“p”,我该怎么办?
我有一个canvas with text ,
ctx.beginPath();
ctx.fillText('Hello yyyqqqppp', 50, 50);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
我该怎么做才能在它周围绘制矩形?
提前致谢!
最佳答案
以下是在文本周围绘制矩形的一些关键
如果您希望文本从左上角对齐,则可以设置这些上下文对齐属性:
context.textAlign='left'; // this is the default to align horizontally to the left
context.textBaseline='top'; // text will be aligned vertically to the top
您可以使用此上下文方法测量文本的水平宽度:
// set the font size and font face before measuring
context.font='14px verdana';
var textWidth=context.measureText('Hello').width;
没有原生 Canvas 方法来测量文本高度,但对于我合作过的大多数字体和非极端字体大小,您可以获得高度的近似值,如下所示:
var lineHeight=fontsizeInPixels * 1.286;
示例代码和演示:
// get references to canvas and context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var fontsize = 14;
var fontface = 'verdana';
var lineHeight = fontsize * 1.286;
var text = 'Draw a rectangle around me.';
ctx.font = fontsize + 'px ' + fontface;
var textWidth = ctx.measureText(text).width;
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText(text, 20, 50);
ctx.strokeRect(20, 50, textWidth, lineHeight);
canvas {
border: 1px solid red;
}
<canvas id=canvas width=300 height=300></canvas>
关于javascript - 如何在 html Canvas 中围绕文本绘制矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33137588/