[英]How do I get the position of text top line using JavaScript
I am looking at a Daniel Earwicker's answer to "How can you find the height of text on an HTML canvas?". 我正在看Daniel Touwicker的回答 “如何在HTML画布上找到文本的高度?”。
It provides me with a way to get certain metrics on text height. 它为我提供了一种获取文本高度的特定指标的方法。
However what I am interested in is getting the metric for a black line below: 但是我感兴趣的是获得下面黑线的指标:
Is it possible to get it using this approach? 是否有可能使用这种方法?
See http://jsfiddle.net/BL5nP (hardcoded black line). 见http://jsfiddle.net/BL5nP (硬编码黑线)。
HTML: HTML:
<canvas width="500" height="500"></canvas>
JavaScript: JavaScript的:
// function from https://stackoverflow.com/questions/1134586/how-can-you-find-the-height-of-text-on-an-html-canvas/9847841#answer-9847841
var getTextHeight = function(font)
{
var text = $('<span>Ag</span>');
text[0].style.font = font;
var block = $('<div style="display: inline-block; width: 1px; height: 0px;"></div>');
var div = $('<div></div>');
div.append(text, block);
var body = $('body');
body.append(div);
try
{
var result = {};
block.css({ verticalAlign: 'baseline' });
result.ascent = block.offset().top - text.offset().top;
block.css({ verticalAlign: 'bottom' });
result.height = block.offset().top - text.offset().top;
result.descent = result.height - result.ascent;
}
finally
{
div.remove();
}
return result;
};
var testLine = function(ctx, x, y, len, style)
{
ctx.strokeStyle = style;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + len, y);
ctx.closePath();
ctx.stroke();
};
var ctx = $('canvas')[0].getContext('2d');
var x = 10;
var y = 10;
var font = '36pt Times';
var message = 'ABCD';
ctx.fillStyle = 'black';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.font = font;
ctx.fillText(message, x, y);
var w = ctx.measureText(message).width;
var h = getTextHeight(font);
testLine(ctx, x, y, w, 'red');
testLine(ctx, x, y + h.ascent, w, 'green');
testLine(ctx, x, y + h.height, w, 'blue');
testLine(ctx, x, y + 10, w, 'black'); // this line is what I am interested in
There is this small fontmetrics library that does the trick https://github.com/Pomax/fontmetrics.js 有一个小的fontmetrics库可以解决这个问题https://github.com/Pomax/fontmetrics.js
The only reliable method to get the ascent (top of letter l) is to simply draw the text on the canvas and count white lines until top boundary is visible (this is what the library above does). 获得上升(字母l的顶部)的唯一可靠方法是简单地在画布上绘制文本并计算白线直到顶部边界可见(这是上面的库所做的)。
There are couple of approximations by aligning inline spans and divs, but none of them gives reliable cross-browser results. 通过对齐内联跨度和div,有几个近似值,但它们都没有提供可靠的跨浏览器结果。 Eg this one relies on getBoundingClientRect()
and can be made to work in certain limited cases, but not in general: http://jsfiddle.net/Exceeder/rP7Jj/ 例如,这个依赖于getBoundingClientRect()
并且可以在某些有限的情况下工作,但不是一般的: http : //jsfiddle.net/Exceeder/rP7Jj/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.