宽度很简单:画布的上下文有一个内置的度量来测量文本宽度。
// this will measure text width
context.font = '14pt Verdana';
var m=context.measureText(yourText);
var theWidth=m.width;
高度更困难,因为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;
}