이전의 좋은 답변을 바탕으로 구축하십시오. 이것은 높이와 너비 (일부 유니 코드 문자 및 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);
}
먼저 답장을 보내 주셔서 감사합니다. 나는이 솔루션에 대해서도 생각했지만 이 솔루션은 덜 효율적이며 내 "효율적인"웹 사이트와 일치하지 않습니다. 더 좋은 방법은 없을까요? –
이 코드는 효율적으로 사용하면 매우 효율적입니다! ** 다양한 글꼴에 대해이 코드를 한 번만 실행하면됩니다 **. 그럼 너는 영원히 너에게 높이가있다! 글꼴 크기를 픽셀 단위로 설정하면 웹 사이트를 공개하고 웹 사이트에서 사용할 수 있도록 JSON에 높이를 저장하기 전에 글꼴 크기를 설정할 수도 있습니다. 쉽고 효율적! BTW,이 코드는 초당 수백 번 실행되므로 실제로 동적으로 수행 할 수도 있습니다. ;) – markE
물론 나는이 방법으로 시간을 절약 할 수 있습니다.하지만 저는 상징을 나타내는 캐릭터를 그리는 중입니다. 캐릭터마다 크기가 다릅니다. 그리고 그런. .. 그러나 나는 다른 길은 없다고 생각한다. 감사합니다. –