Width is easy: canvas's context has a built in metric for measuring text width.
// this will measure text width
context.font = '14pt Verdana';
var m=context.measureText(yourText);
var theWidth=m.width;
Height is more difficult because measureText doesn't compute height.
You can often use the font size to approximate the height--that's what I do.
But if you really need more accuracy here is a function that examines the text's pixels to calculate its height:
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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…