最近在做智能图片相关问题,关于文字高度居中方案反复做了不少尝试。

canvas有textAlign和textBaseline两个属性设置文字的对应方式。但是这两个属性是用来设置文本内整体的对齐方式,无法实现在在一个整体居中。

文字结构:

就像是写字的时候一样,分为上中下田子方格。真正的字体区分中文,英文的大小写,在上下两行,不同的字,在上下结构中,并没有占据完全,或者说文字中存在一定的阴影,会有存在一定的像素值。

解决方案:

方案一:

canvas有text的measureText方法可以获取TextMetrics对象中包含了text的文字信息。通过TextMetrics我们可以直接获得文字的width值。但是没有直接获得height值。

TextMetrics提供了actualBoundingBoxAscent和actualBoundingBoxDescent两个属性。可以参考https://developer.mozilla.org/zh-CN/docs/Web/API/TextMetrics

let metrics = ctx.measureText(text); 
let fontHeight = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent; 
//所有字在这个字体下的高度
let actualHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent; 
// 当前文本字符串在这个字体下用的实际高度

const fix = ctx.measureText(text).actualBoundingBoxAscent + ctx.measureText(text).actualBoundingBoxDescent;
ctx.fillText(text, width / 2, height / 2  + fix/ 2);

方法二:

将要测量的文字放在dom中获取其高度

let getTextHeight = function(font,size) {
	var text = document.createElement('span');
	text.style['fontFamily'] = font ;
	text.style['fontSize'] = size ;
	text.innerHTML = "H";
	var block = document.createElement('div') ;
	block.style.display ="inline-block";
	block.style.width = "1px" ;
	block.style.height = "0px" ; 
	var div = document.createElement('div');
	div.appendChild(text);
	div.appendChild(block)
	document.body.appendChild(div);
	var height = 0 ;
	try {
		block.style.verticalAlign = "bottom" ;
		height = block.offsetTop - text.offsetTop;
	} finally {
		div.remove();
	}
	return height;
}

用这个高度实现的垂直居中跟直接设置textBaseline = 'middle'效果是一样的。在dom中所测量的高度也对应了TextMetrics的fontBoundingBoxAscent属性和fontBoundingBoxDescent属性。

测试了下不同字体和大小下两者差值在1~2px。原因可能在于dom获取的lineHeight中包含了上下的leading。

但是像是前文说到的,我们需要的仅仅文字的高度,这个田子方格的高度。

所以尝试通过像素点来获得黑色区域的区域,如果我们的背景不设置的话,只有透明度不为0,就说明存在像素值。

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.font = ‘.....’;
ctx.fillStyle = '...';
ctx?.fillText(..., ..., ...);
const imgDt = ctx?.getImageData(0, 0, 50, 40);
  const data = imgDt?.data;
  console.log('imgDt', data[3], imgDt);
  let arr = [];
  for (let y = 0; y < 40; y++) {
    for (let x = 0; x < 50; x++) {
      let index = (y * 50 + x) * 4;
      let r = data[index];
      let g = data[index + 1];
      let b = data[index + 2];
      let a = data[index + 3];
      console.log('getCanvasHeight', index, r, g, b, a);
      if (a !== 0) {
        arr.push({ x, y, index }); //y的最小值和最大值的差就是高度
      }
    }
  }

补充一点,我们绘制图片也可以采用pixi,pixi获得文字的话,可以将文字直接转为图片,这样在不设置宽高的前提的情况下,默认会将舞台中的内容贴边转化,这样直接获得图片的宽高,就可以得到文字的宽高。

如何在HTML画布上找到文本的高度?

规范有一个文本(context.measureText)函数,它将告诉您打印文本需要多大宽度,但我找不到一种方法来确定它有多高。我知道它是基于字体的,但我不知道如何将字体字符串转换为文本高度。

//上篇提到的与答案11.类似

1.

通过检查大写字母M的长度,可以得到与垂直高度非常接近的高度。

ctx.font = 'bold 10px Arial';

lineHeight = ctx.measureText('M').width;

2.

画布规范没有给我们一种测量绳子高度的方法。但是,您可以以像素为单位设置文本的大小,并且通常可以相对容易地计算出垂直边界。

如果您需要更精确的内容,那么您可以将文本放到画布上,然后获取像素数据,并计算出垂直使用了多少像素。这将是相对简单的,但效率不是很高。你可以这样做(它可以工作,但是在你的画布上绘制一些你想要删除的文本):

function measureTextHeight(ctx, left, top, width, height) {

    // Draw the text in the specified area
    ctx.save();
    ctx.translate(left, top + Math.round(height * 0.8));
    ctx.mozDrawText('gM'); // This seems like tall text...  Doesn't it?
    ctx.restore();

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

    // Find the last line with a non-white 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-white 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;
    }

    // We screwed something up...  What do you expect from free code?
    return 0;
}

// Set the font
context.mozTextStyle = '32px Arial';

// Specify a context and a rect that is safe to draw in when calling measureTextHeight
var height = measureTextHeight(context, 0, 0, 50, 50);
console.log(height);

对于Bespin,他们通过测量小写‘m’的宽度来伪造高度。我不知道这是如何使用的,我也不推荐使用这种方法。下面是相关的Bespin方法:

var fixCanvas = function(ctx) {
    // upgrade Firefox 3.0.x text rendering to HTML 5 standard
    if (!ctx.fillText && ctx.mozDrawText) {
        ctx.fillText = function(textToDraw, x, y, maxWidth) {
            ctx.translate(x, y);
            ctx.mozTextStyle = ctx.font;
            ctx.mozDrawText(textToDraw);
            ctx.translate(-x, -y);
        }
    }

    if (!ctx.measureText && ctx.mozMeasureText) {
        ctx.measureText = function(text) {
            ctx.mozTextStyle = ctx.font;
            var width = ctx.mozMeasureText(text);
            return { width: width };
        }
    }

    if (ctx.measureText && !ctx.html5MeasureText) {
        ctx.html5MeasureText = ctx.measureText;
        ctx.measureText = function(text) {
            var textMetrics = ctx.html5MeasureText(text);

            // fake it 'til you make it
            textMetrics.ascent = ctx.html5MeasureText("m").width;

            return textMetrics;
        }
    }

    // for other browsers
    if (!ctx.fillText) {
        ctx.fillText = function() {}
    }

    if (!ctx.measureText) {
        ctx.measureText = function() { return 10; }
    }
};

3.

如果您使用context.font定义字体,以像素为单位的文本高度是否等于字体大小(以pt为单位)?

4.

正如JJ Stiff建议的那样,您可以将文本添加到范围中,然后测量该范围的offsetHeight。

var d = document.createElement("span");
d.font = "20px arial";
d.textContent = "Hello world!";
document.body.appendChild(d);
var emHeight = d.offsetHeight;
document.body.removeChild(d);

复制

HTML5Rocks所示

5.

我直接解决了这个问题--使用像素操作。

以下是图形化的答案:

;

下面是代码:

    function textHeight (text, font) {

    var fontDraw = document.createElement("canvas");

    var height = 100;
    var width = 100;

    // here we expect that font size will be less canvas geometry
    fontDraw.setAttribute("height", height);
    fontDraw.setAttribute("width", width);

    var ctx = fontDraw.getContext('2d');
    // black is default
    ctx.fillRect(0, 0, width, height);
    ctx.textBaseline = 'top';
    ctx.fillStyle = 'white';
    ctx.font = font;
    ctx.fillText(text/*'Eg'*/, 0, 0);

    var pixels = ctx.getImageData(0, 0, width, height).data;

    // row numbers where we first find letter end where it ends 
    var start = -1;
    var end = -1;

    for (var row = 0; row < height; row++) {
        for (var column = 0; column < width; column++) {

            var index = (row * width + column) * 4;

            // if pixel is not white (background color)
            if (pixels[index] == 0) {
                // we havent met white (font color) pixel
                // on the row and the letters was detected
                if (column == width - 1 && start != -1) {
                    end = row;
                    row = height;
                    break;
                }
                continue;
            }
            else {
                // we find top of letter
                if (start == -1) {
                    start = row;
                }
                // ..letters body
                break;
            }

        }

    }
   /*
    document.body.appendChild(fontDraw);
    fontDraw.style.pixelLeft = 400;
    fontDraw.style.pixelTop = 400;
    fontDraw.style.position = "absolute";
   */

    return end - start;

}

6.

一行答案

var height = parseInt(ctx.font) * 1.2; 

CSS "line-height: normal“介于1和1.2之间

有关更多信息,请阅读here

7.

这是我基于这里的一些其他答案所做的:

function measureText(text, font) {
	const span = document.createElement('span');
	span.appendChild(document.createTextNode(text));
	Object.assign(span.style, {
		font: font,
		margin: '0',
		padding: '0',
		border: '0',
		whiteSpace: 'nowrap'
	});
	document.body.appendChild(span);
	const {width, height} = span.getBoundingClientRect();
	span.remove();
	return {width, height};
}

var font = "italic 100px Georgia";
var text = "abc this is a test";
console.log(measureText(text, font));

8.

我正在写一个终端模拟器,所以我需要在字符周围画矩形。

var size = 10
var lineHeight = 1.2 // CSS "line-height: normal" is between 1 and 1.2
context.font = size+'px/'+lineHeight+'em monospace'
width = context.measureText('m').width
height = size * lineHeight

显然,如果你想要角色所占空间的确切大小,这是没有帮助的。但对于某些用途,它会给你一个很好的近似值。

9.

下面是一个简单的函数。不需要库。

我写这个函数是为了得到相对于基线的上下限。如果textBaseline设置为alphabetic。它所做的是创建另一个画布,然后在那里绘制,然后找到最顶部和最底部的非空白像素。这是上界和下界。它将其作为相对值返回,因此如果height为20px,并且基线以下没有任何内容,则上限为-20

您必须为其提供字符。否则,很明显它会给你0的高度和0的宽度。

用法:

alert(measureHeight('40px serif', 40, 'rg').height)

下面是函数:

function measureHeight(aFont, aSize, aChars, aOptions={}) {
    // if you do pass aOptions.ctx, keep in mind that the ctx properties will be changed and not set back. so you should have a devoted canvas for this
    // if you dont pass in a width to aOptions, it will return it to you in the return object
    // the returned width is Math.ceil'ed
    console.error('aChars: "' + aChars + '"');
    var defaultOptions = {
        width: undefined, // if you specify a width then i wont have to use measureText to get the width
        canAndCtx: undefined, // set it to object {can:,ctx:} // if not provided, i will make one
        range: 3
    };

    aOptions.range = aOptions.range || 3; // multiples the aSize by this much

    if (aChars === '') {
        // no characters, so obviously everything is 0
        return {
            relativeBot: 0,
            relativeTop: 0,
            height: 0,
            width: 0
        };
        // otherwise i will get IndexSizeError: Index or size is negative or greater than the allowed amount error somewhere below
    }

    // validateOptionsObj(aOptions, defaultOptions); // not needed because all defaults are undefined

    var can;
    var ctx; 
    if (!aOptions.canAndCtx) {
        can = document.createElement('canvas');;
        can.mozOpaque = 'true'; // improved performanceo on firefox i guess
        ctx = can.getContext('2d');

        // can.style.position = 'absolute';
        // can.style.zIndex = 10000;
        // can.style.left = 0;
        // can.style.top = 0;
        // document.body.appendChild(can);
    } else {
        can = aOptions.canAndCtx.can;
        ctx = aOptions.canAndCtx.ctx;
    }

    var w = aOptions.width;
    if (!w) {
        ctx.textBaseline = 'alphabetic';
        ctx.textAlign = 'left'; 
        ctx.font = aFont;
        w = ctx.measureText(aChars).width;
    }

    w = Math.ceil(w); // needed as i use w in the calc for the loop, it needs to be a whole number

    // must set width/height, as it wont paint outside of the bounds
    can.width = w;
    can.height = aSize * aOptions.range;

    ctx.font = aFont; // need to set the .font again, because after changing width/height it makes it forget for some reason
    ctx.textBaseline = 'alphabetic';
    ctx.textAlign = 'left'; 

    ctx.fillStyle = 'white';

    console.log('w:', w);

    var avgOfRange = (aOptions.range + 1) / 2;
    var yBaseline = Math.ceil(aSize * avgOfRange);
    console.log('yBaseline:', yBaseline);

    ctx.fillText(aChars, 0, yBaseline);

    var yEnd = aSize * aOptions.range;

    var data = ctx.getImageData(0, 0, w, yEnd).data;
    // console.log('data:', data)

    var botBound = -1;
    var topBound = -1;

    // measureHeightY:
    for (y=0; y<=yEnd; y++) {
        for (var x = 0; x < w; x += 1) {
            var n = 4 * (w * y + x);
            var r = data[n];
            var g = data[n + 1];
            var b = data[n + 2];
            // var a = data[n + 3];

            if (r+g+b > 0) { // non black px found
                if (topBound == -1) { 
                    topBound = y;
                }
                botBound = y; // break measureHeightY; // dont break measureHeightY ever, keep going, we till yEnd. so we get proper height for strings like "`." or ":" or "!"
                break;
            }
        }
    }

    return {
        relativeBot: botBound - yBaseline, // relative to baseline of 0 // bottom most row having non-black
        relativeTop: topBound - yBaseline, // relative to baseline of 0 // top most row having non-black
        height: (botBound - topBound) + 1,
        width: w// EDIT: comma has been added to fix old broken code.
    };
}

relativeBotrelativeTopheight是返回对象中的有用内容。

示例用法如下:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
function measureHeight(aFont, aSize, aChars, aOptions={}) {
	// if you do pass aOptions.ctx, keep in mind that the ctx properties will be changed and not set back. so you should have a devoted canvas for this
	// if you dont pass in a width to aOptions, it will return it to you in the return object
	// the returned width is Math.ceil'ed
	console.error('aChars: "' + aChars + '"');
	var defaultOptions = {
		width: undefined, // if you specify a width then i wont have to use measureText to get the width
		canAndCtx: undefined, // set it to object {can:,ctx:} // if not provided, i will make one
		range: 3
	};
	
	aOptions.range = aOptions.range || 3; // multiples the aSize by this much
	
	if (aChars === '') {
		// no characters, so obviously everything is 0
		return {
			relativeBot: 0,
			relativeTop: 0,
			height: 0,
			width: 0
		};
		// otherwise i will get IndexSizeError: Index or size is negative or greater than the allowed amount error somewhere below
	}
	
	// validateOptionsObj(aOptions, defaultOptions); // not needed because all defaults are undefined
	
	var can;
	var ctx; 
	if (!aOptions.canAndCtx) {
		can = document.createElement('canvas');;
		can.mozOpaque = 'true'; // improved performanceo on firefox i guess
		ctx = can.getContext('2d');
		
		// can.style.position = 'absolute';
		// can.style.zIndex = 10000;
		// can.style.left = 0;
		// can.style.top = 0;
		// document.body.appendChild(can);
	} else {
		can = aOptions.canAndCtx.can;
		ctx = aOptions.canAndCtx.ctx;
	}
	
	var w = aOptions.width;
	if (!w) {
		ctx.textBaseline = 'alphabetic';
		ctx.textAlign = 'left';	
		ctx.font = aFont;
		w = ctx.measureText(aChars).width;
	}
	
	w = Math.ceil(w); // needed as i use w in the calc for the loop, it needs to be a whole number
	
	// must set width/height, as it wont paint outside of the bounds
	can.width = w;
	can.height = aSize * aOptions.range;
	
	ctx.font = aFont; // need to set the .font again, because after changing width/height it makes it forget for some reason
	ctx.textBaseline = 'alphabetic';
	ctx.textAlign = 'left';	
	
	ctx.fillStyle = 'white';
	
	console.log('w:', w);
	
	var avgOfRange = (aOptions.range + 1) / 2;
	var yBaseline = Math.ceil(aSize * avgOfRange);
	console.log('yBaseline:', yBaseline);
	
	ctx.fillText(aChars, 0, yBaseline);
	
	var yEnd = aSize * aOptions.range;
	
	var data = ctx.getImageData(0, 0, w, yEnd).data;
	// console.log('data:', data)
	
	var botBound = -1;
	var topBound = -1;
	
	// measureHeightY:
	for (y=0; y<=yEnd; y++) {
		for (var x = 0; x < w; x += 1) {
			var n = 4 * (w * y + x);
			var r = data[n];
			var g = data[n + 1];
			var b = data[n + 2];
			// var a = data[n + 3];
			
			if (r+g+b > 0) { // non black px found
				if (topBound == -1) { 
					topBound = y;
				}
				botBound = y; // break measureHeightY; // dont break measureHeightY ever, keep going, we till yEnd. so we get proper height for strings like "`." or ":" or "!"
				break;
			}
		}
	}
	
	return {
		relativeBot: botBound - yBaseline, // relative to baseline of 0 // bottom most row having non-black
		relativeTop: topBound - yBaseline, // relative to baseline of 0 // top most row having non-black
		height: (botBound - topBound) + 1,
		width: w
	};
}

</script>
</head>
<body style="background-color:steelblue;">
<input type="button" value="reuse can" onClick="alert(measureHeight('40px serif', 40, 'rg', {canAndCtx:{can:document.getElementById('can'), ctx:document.getElementById('can').getContext('2d')}}).height)">
<input type="button" value="dont reuse can" onClick="alert(measureHeight('40px serif', 40, 'rg').height)">
<canvas id="can"></canvas>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

relativeBotrelativeTop是您在此图中看到的内容:

Drawing text - Web APIs | MDN

;

10.

我已经实现了一个很好的库,用于使用HTML canvas测量文本的确切高度和宽度。这应该可以做你想要的事情。

GitHub - ChrisBellew/text-measurer.js: Measure the exact height of text in the browser using JavaScript

11.

我对这里没有正确的答案感到有点震惊。没有必要进行估计或猜测。而且,font-size不是字体边界框的实际大小。字体高度取决于您是否有升序和降序。

要计算它,请使用ctx.measureText()并将actualBoundingBoxAscentactualBoundingBoxDescent相加。这会给你实际的尺寸。您还可以将这两个font*版本相加,以获得用于计算诸如元素高度之类的内容的大小,但不是严格意义上的字体实际使用空间的高度。

const text = 'Hello World';
const canvas = document.querySelector('canvas');
canvas.width = 500;
canvas.height = 200;

const ctx = canvas.getContext('2d');

ctx.font = '100px Arial, Helvetica, sans-serif';
// top is critical to the fillText() calculation
// you can use other positions, but you need to adjust the calculation
ctx.textBaseline = 'top';
ctx.textAlign = 'center';

const metrics = ctx.measureText(text);
const width = metrics.width;
const actualHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
const fontHeight = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent;

ctx.fillStyle = '#00F'; // blue
ctx.fillRect((canvas.width / 2) - (width / 2), (canvas.height / 2) - (fontHeight / 2), width, fontHeight);

ctx.fillStyle = '#0F0'; // green
ctx.fillRect((canvas.width / 2) - (width / 2), (canvas.height / 2) - (actualHeight / 2), width, actualHeight);

// canvas.height / 2 - actualHeight / 2 gets you to the top of
// the green box. You have to add actualBoundingBoxAscent to shift
//  it just right
ctx.fillStyle = '#F00'; // red
ctx.fillText(text, canvas.width / 2, canvas.height / 2 - actualHeight / 2 + metrics.actualBoundingBoxAscent);

<canvas></canvas>

12.

有趣的是,TextMetrics只有宽度,没有高度:

HTML Standard

你能像这个例子一样使用Span吗?

HTML5: Typographic Metrics | Galactic.ink

13.

首先,你需要设置一个字体的高度大小,然后根据字体高度的值来确定你当前的文本高度是多少,交叉文本行,当然,同样的字体高度也需要累加,如果文本没有超过文本框的最大高度,则全部显示,否则,只显示文本框内的文本。高值需要你自己的定义。预设高度越大,需要显示和截取的文本的高度就越大。

After the effect is processed(solve)

Before the effect is processed( unsolved)

  AutoWrappedText.auto_wrap = function(ctx, text, maxWidth, maxHeight) {
var words = text.split("");
var lines = [];
var currentLine = words[0];

var total_height = 0;
for (var i = 1; i < words.length; i++) {
    var word = words[i];
    var width = ctx.measureText(currentLine + word).width;
    if (width < maxWidth) {
        currentLine += word;
    } else {
        lines.push(currentLine);
        currentLine = word;
        // TODO dynamically get font size
        total_height += 25;

        if (total_height >= maxHeight) {
          break
        }
    }
}
if (total_height + 25 < maxHeight) {
  lines.push(currentLine);
} else {
  lines[lines.length - 1] += "…";
}
return lines;};

14.

我在我的一个项目中修补了CanvasRenderingContext2D.measureText(),以包含文本的实际高度。它是用普通的JS编写的,没有依赖项。

/*
 * Monkeypatch CanvasRenderingContext2D.measureText() to include actual height of the text
 */
; (function (global) {
  "use strict";

  var _measureText = global.CanvasRenderingContext2D.prototype.measureText;

  global.CanvasRenderingContext2D.prototype.measureText = function () {
    var textMetrics = _measureText.apply(this, arguments);

    var _getHeight = function (text) {
      var $span = global.document.createElement("span");
      var spanTextNode = global.document.createTextNode(text);
      $span.appendChild(spanTextNode);
      $span.setAttribute("style", `font: ${this.font}`);

      var $div = global.document.createElement("div");
      $div.setAttribute("style", "display: inline-block; width: 1px; height: 0; vertical-align: super;");

      var $parentDiv = global.document.createElement("div");
      $parentDiv.appendChild($span);
      $parentDiv.appendChild($div);

      var $body = global.document.getElementsByTagName("body")[0];
      $body.appendChild($parentDiv);

      var divRect = $div.getBoundingClientRect();
      var spanRect = $span.getBoundingClientRect();
      var result = {};

      $div.style.verticalAlign = "baseline";
      result.ascent = divRect.top - spanRect.top;

      $div.style.verticalAlign = "bottom";
      result.height = divRect.top - spanRect.top;

      result.descent = result.height - result.ascent;

      $body.removeChild($parentDiv);

      return result.height - result.descent;
    }.bind(this);

    var height = _getHeight(arguments[0]);

    global.Object.defineProperty(textMetrics, "height", { value: height });

    return textMetrics;
  };

})(window);

您可以像这样使用它

ctx.font = "bold 64px Verdana, sans-serif"; // Automatically considers it as part of height calculation
var textMetrics = ctx.measureText("Foobar");
var textHeight = textMetrics.height;

15.

我知道这是一个老生常谈的问题,但为了将来参考,我想添加一个简短的、最小的、仅限JS(没有jquery)的解决方案,我相信人们可以从中受益:

var measureTextHeight = function(fontFamily, fontSize) 
{
    var text = document.createElement('span');
    text.style.fontFamily = fontFamily;
    text.style.fontSize = fontSize + "px";
    text.textContent = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
    document.body.appendChild(text);
    var result = text.getBoundingClientRect().height;
    document.body.removeChild(text);
    return result;
};

16.

这适用于1)多行文本以及2)甚至在IE9中!

<div class="measureText" id="measureText">
</div>


.measureText {
  margin: 0;
  padding: 0;
  border: 0;
  font-family: Arial;
  position: fixed;
  visibility: hidden;
  height: auto;
  width: auto;
  white-space: pre-wrap;
  line-height: 100%;
}

function getTextFieldMeasure(fontSize, value) {
    const div = document.getElementById("measureText");

    // returns wrong result for multiline text with last line empty
    let arr = value.split('\n');
    if (arr[arr.length-1].length == 0) {
        value += '.';
    }

    div.innerText = value;
    div.style['font-size']= fontSize + "px";
    let rect = div.getBoundingClientRect();

    return {width: rect.width, height: rect.height};
};

17.

设置字体大小可能并不实用,因为设置

ctx.font = '‘

将使用CSS定义的字体标签以及任何嵌入的字体标签。如果你使用CSS字体,你不知道高度是多少从编程的方式,使用measureText方法,这是非常短视的。但从另一方面来说,IE8确实返回了宽度和高度。

18.

parseInt(ctx.font, 10)

例如:

let text_height = parseInt(ctx.font, 10)

例如,返回35

19.

在正常情况下,以下操作应该有效:

var can = CanvasElement.getContext('2d');          //get context
var lineHeight = /[0-9]+(?=pt|px)/.exec(can.font); //get height from font variable

20.

近似解:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "100px Arial";
var txt = "Hello guys!"
var wt = ctx.measureText(txt).width;
var height = wt / txt.length;

21.

这是疯狂的..。文本的高度是字体大小。你们中有没有人读过文档?

context.font = "22px arial";

这会将高度设置为22px。

唯一的原因是..。

context.measureText(string).width

是因为字符串的宽度是无法确定的,除非它知道您想要的字符串的宽度,而不是所有用字体绘制的字符串。高度将是22px。

如果你使用px以外的其他测量值,那么高度仍然是相同的,但是使用该测量值,所以最多你需要做的就是转换测量值。

转载于:canvas绘制获得文字高度方案 - 知乎

如何在HTML画布上找到文本的高度? - 问答 - 腾讯云开发者社区-腾讯云

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐