只是建立在以前的好答案的基础上。这将给出高度和宽度(我对一些 unicode 字符和 measureText 有一些问题,这是某些字符的唯一解决方案)。
function measureTextHeight(fontSizeFace, text) {
var width = 1500;
var height = 500;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx=canvas.getContext("2d");
ctx.save();
ctx.font=fontSizeFace;
ctx.clearRect(0,0,width,height);
ctx.fillText(text, parseInt(width * 0.1, 10), parseInt(height / 2, 10));
ctx.restore();
document.body.appendChild(canvas);
var data = ctx.getImageData(0,0,width,height).data;
var topMost = false;
var bottomMost = false;
var leftMost = false;
var rightMost = false;
for(var x=0; x<width; x++) {
for(var y=0; (y<height) && (!leftMost); y++) {
//console.log("x: %s y: %s index: %s", x,y, getAlphaIndexForCoordinates(x,y,width,height).toString() );
if(data[getAlphaIndexForCoordinates(x,y,width,height)] != 0) {
leftMost = x;
}
}
}
for(var y=0; y<height; y++) {
for(var x=0; (x<width) && (!topMost); x++) {
//console.log("x: %s y: %s index: %s", x,y, getAlphaIndexForCoordinates(x,y,width,height).toString() );
if(data[getAlphaIndexForCoordinates(x,y,width,height)] != 0) {
topMost = y;
}
}
}
for(var x=width-1; x>=0; x--) {
for(var y=height-1; (y>=0) && (!rightMost); y--) {
//console.log("x: %s y: %s index: %s", x,y, getAlphaIndexForCoordinates(x,y,width,height).toString() );
if(data[getAlphaIndexForCoordinates(x,y,width,height)] != 0) {
rightMost = x;
}
}
}
for(var y=height-1; y>=0; y--) {
for(var x=width-1; (x>=0) && (!bottomMost); x--) {
//console.log("x: %s y: %s index: %s", x,y, getAlphaIndexForCoordinates(x,y,width,height).toString() );
if(data[getAlphaIndexForCoordinates(x,y,width,height)] != 0) {
bottomMost = y;
}
}
}
return ({
width: (rightMost - leftMost) + 1
,height: (bottomMost - topMost) + 1
});
}
function getAlphaIndexForCoordinates(x,y,width,height) {
return (((width*4*y)+4*x)+3);
}