在javascript中计算确切的字符\字符串高度

Raz*_*a O 0 javascript height canvas character measure

我正在使用画布,我想不出任何解决方案,或在我的问题上找到答案.

我有一个字体,其中包含不同大小的符号\字符 - 高度和宽度.

我想从字体中绘制一些字符(符号),在符号的顶部\下面绘制一些字符.问题是我无法找到一种方法来获得我正在绘制的角色的精确高度(以像素为单位),并且它会导致中心符号与顶部\下方的符号之间出现不需要的空间(以获得宽度)一个字符串,有函数context.measureText(theText)).

对于前 让我说我希望'X'成为我的中心符号.和' - '在顶部.它看起来像这样

-
x

但现在'X'和' - '之间有空间,我不想要.

谁能帮我这个 ?

谢谢

mar*_*rkE 5

宽度很简单:画布的上下文具有用于测量文本宽度的内置度量.

// this will measure text width
context.font = '14pt Verdana';
var m=context.measureText(yourText);
var theWidth=m.width;
Run Code Online (Sandbox Code Playgroud)

高度更难,因为measureText不计算高度.

您通常可以使用字体大小来估算高度 - 这就是我的工作.

但是如果你真的需要更高的精确度,这里有一个功能可以检查文本的像素来计算它的高度:

function measureTextHeight(fontSizeFace) {

    // create a temp canvas
    var width=1000;
    var height=60;
    var canvas=document.createElement("canvas");
    canvas.width=width;
    canvas.height=height;
    var ctx=canvas.getContext("2d");

    // Draw the entire a-z/A-Z alphabet in the canvas
    var text="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    ctx.save();
    ctx.font=fontSizeFace;
    ctx.clearRect(0,0,width,height);
    ctx.fillText(text, 0, 40);
    ctx.restore();

    // Get the pixel data from the canvas
    var data = ctx.getImageData(0,0,width,height).data,
        first = false, 
        last = false,
        r = height,
        c = 0;

    // Find the last line with a non-transparent pixel
    while(!last && r) {
        r--;
        for(c = 0; c < width; c++) {
            if(data[r * width * 4 + c * 4 + 3]) {
                last = r;
                break;
            }
        }
    }

    // Find the first line with a non-transparent pixel
    while(r) {
        r--;
        for(c = 0; c < width; c++) {
            if(data[r * width * 4 + c * 4 + 3]) {
                first = r;
                break;
            }
        }

        // If we've got it then return the height
        if(first != r) return last - first;
    }

    // error condition if we get here
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您有效地使用它,此代码非常有效!请记住,您只需要针对各种字体运行此代码**.然后你永远拥有你的高度!如果您设置字体大小(以像素为单位),您甚至可以在发布网站之前执行此操作,并将高度存储在JSON中以便在您的网站上使用.易+高效!顺便说一句,这段代码每秒运行数百次,所以你真的可以动态地执行它.;) (3认同)