font: add 1 to the canvas glyph to avoid clipping

This commit is contained in:
Mitchell Hashimoto
2022-12-05 15:37:55 -08:00
parent 25f2f1a652
commit ed4e8c36b0
2 changed files with 10 additions and 6 deletions

View File

@ -47,8 +47,8 @@ fetch(url.href).then(response =>
const font_ptr = malloc(font.byteLength); const font_ptr = malloc(font.byteLength);
new Uint8Array(memory.buffer, font_ptr).set(font); new Uint8Array(memory.buffer, font_ptr).set(font);
// Call whatever example you want: // Initialize our font face
const face = face_new(font_ptr, font.byteLength, 72); const face = face_new(font_ptr, font.byteLength, 72 /* size in px */);
free(font_ptr); free(font_ptr);
// Render a glyph // Render a glyph

View File

@ -121,13 +121,17 @@ pub const Face = struct {
const bounding_right = try metrics.get(f32, "actualBoundingBoxRight"); const bounding_right = try metrics.get(f32, "actualBoundingBoxRight");
if (bounding_right > 0) break :width bounding_right; if (bounding_right > 0) break :width bounding_right;
break :width try metrics.get(f32, "width"); break :width try metrics.get(f32, "width");
})); })) + 1;
// Height is our ascender + descender for this char // Height is our ascender + descender for this char
const asc = try metrics.get(f32, "actualBoundingBoxAscent"); const asc = try metrics.get(f32, "actualBoundingBoxAscent");
const desc = try metrics.get(f32, "actualBoundingBoxDescent"); const desc = try metrics.get(f32, "actualBoundingBoxDescent");
const left = try metrics.get(f32, "actualBoundingBoxLeft"); const left = try metrics.get(f32, "actualBoundingBoxLeft");
const height = @floatToInt(u32, @ceil(asc + desc)); const height = @floatToInt(u32, @ceil(asc + desc)) + 1;
// Note: width and height both get "+ 1" added to them above. This
// is important so that there is a 1px border around the glyph to avoid
// any clipping in the atlas.
// Resize canvas to match the glyph size exactly // Resize canvas to match the glyph size exactly
{ {
@ -163,8 +167,8 @@ pub const Face = struct {
try ctx.set("fillStyle", js.string("black")); try ctx.set("fillStyle", js.string("black"));
try ctx.call(void, "fillText", .{ try ctx.call(void, "fillText", .{
glyph_str, glyph_str,
left, left + 1,
asc, asc + 1,
}); });
// Read the image data and get it into a []u8 on our side // Read the image data and get it into a []u8 on our side