ここで以前の良い答えに基づいて構築するだけです。これにより、高さと幅が得られます(一部のユニコード文字とメジャーテキストに問題がありましたが、これが一部の文字の唯一の解決策でした)。
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);
}