Skip to content

Commit 6fbd465

Browse files
committed
Simplified/fixed font metrix on wasm
1 parent 90e7d38 commit 6fbd465

File tree

1 file changed

+5
-40
lines changed

1 file changed

+5
-40
lines changed

nimx/private/font/web_glyph_provider.nim

Lines changed: 5 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -22,46 +22,11 @@ proc cssFontName(p: WebGlyphProvider): string =
2222
template clearCache*(p: WebGlyphProvider) = discard
2323

2424
proc calculateFontMetricsInCanvas(n: cstring, fontSize: int, o: pointer) {.importwasmraw: """
25-
// Idea borrowed from from https://github.com/Pomax/fontmetrics.js
26-
var textstring = "Hl@¿Éq¶", n = _nimsj($0);
27-
var canvas = document.createElement("canvas");
28-
var ctx = canvas.getContext("2d");
29-
ctx.font = n;
30-
var m = ctx.measureText(textstring);
31-
32-
var padding = 100;
33-
canvas.width = m.width + padding;
34-
canvas.height = 3*$1;
35-
canvas.style.opacity = 1;
36-
ctx.font = n;
37-
var w = canvas.width,
38-
h = canvas.height,
39-
baseline = h/2;
40-
41-
// Set all canvas pixeldata values to 255, with all the content
42-
// data being 0. This lets us scan for data[i] != 255.
43-
ctx.fillStyle = "white";
44-
ctx.fillRect(-1, -1, w+2, h+2);
45-
ctx.fillStyle = "black";
46-
ctx.fillText(textstring, padding/2, baseline);
47-
var pixelData = ctx.getImageData(0, 0, w, h).data;
48-
49-
// canvas pixel data is w*4 by h*4, because R, G, B and A are separate,
50-
// consecutive values in the array, rather than stored as 32 bit ints.
51-
var i = 0,
52-
w4 = w * 4,
53-
len = pixelData.length;
54-
55-
// Finding the ascent uses a normal, forward scanline
56-
while (++i < len && pixelData[i] === 255) {}
57-
var ascent = (i/w4)|0;
58-
59-
// Finding the descent uses a reverse scanline
60-
i = len - 1;
61-
while (--i > 0 && pixelData[i] === 255) {}
62-
var descent = (i/w4)|0;
63-
64-
_nimwf([baseline - ascent, descent - baseline], $2);
25+
var c = document.createElement("canvas"),
26+
C = c.getContext("2d");
27+
C.font = _nimsj($0);
28+
var m = C.measureText("Hl@¿Éq¶");
29+
_nimwf([m.actualBoundingBoxAscent, m.fontBoundingBoxDescent], $2)
6530
""".}
6631

6732
proc getFontMetrics*(p: WebGlyphProvider, oAscent, oDescent: var float32) =

0 commit comments

Comments
 (0)