フォントによってボックスの大きさが違うので完璧なサイズを取得するというのは難しいような気がします。
仮にやるならテキストをcanvasに入れて色情報から文字サイズを判別することでできるかもしれません。
keisukeh さんありがとうございます。
以下のコードで求めている大きさを取得できました。
js
1const canvas = document.createElement("canvas")
2const context = canvas.getContext("2d")
3context.font = "16pt 'リュウミン R-KL'"
4context.fillText("永", 0, canvas.height)
5const imageData = context.getImageData(0, 0, canvas.width, canvas.height)
6let bottom, left, right, _top
7
8for (
9 let index = 0,
10 length = imageData.data.length;
11 index < length;
12 index += 4
13) {
14 const a = imageData.data[index + 3]
15 const x = index / 4 % canvas.width
16 const y = Math.floor(index / 4 / canvas.width)
17
18 if (a === 0) {
19 continue
20 }
21
22 if (
23 typeof bottom === "undefined"
24 || bottom < y
25 ) {
26 bottom = y
27 }
28
29 if (
30 typeof left === "undefined"
31 || left > x
32 ) {
33 left = x
34 }
35
36 if (
37 typeof right === "undefined"
38 || right < x
39 ) {
40 right = x
41 }
42
43 if (
44 typeof _top === "undefined"
45 || _top > y
46 ) {
47 _top = y
48 }
49}
50
51{
52 height: bottom - _top,
53 width: right - left,
54}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。