Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: canvas measureText and the drawing methods chart libraries probe

Adrià Arrufatcb8ad6faa6e6
diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zig
index f79297a77..ae7aa8cf9 100644
--- a/src/browser/js/bridge.zig
+++ b/src/browser/js/bridge.zig
@@ -1226,6 +1226,9 @@ pub const PageJsApis = flattenTypes(&.{
@import("../webapi/canvas/WebGLRenderingContext.zig"),
@import("../webapi/canvas/OffscreenCanvas.zig"),
@import("../webapi/canvas/OffscreenCanvasRenderingContext2D.zig"),
+ @import("../webapi/canvas/TextMetrics.zig"),
+ @import("../webapi/canvas/CanvasGradient.zig"),
+ @import("../webapi/canvas/CanvasPattern.zig"),
@import("../webapi/SubtleCrypto.zig"),
@import("../webapi/CryptoKey.zig"),
@import("../webapi/Selection.zig"),
@@ -1295,6 +1298,9 @@ const worker_common_apis = [_]type{
@import("../webapi/URLPattern.zig"),
@import("../webapi/canvas/OffscreenCanvas.zig"),
@import("../webapi/canvas/OffscreenCanvasRenderingContext2D.zig"),
+ @import("../webapi/canvas/TextMetrics.zig"),
+ @import("../webapi/canvas/CanvasGradient.zig"),
+ @import("../webapi/canvas/CanvasPattern.zig"),
@import("../webapi/net/XMLHttpRequest.zig"),
@import("../webapi/net/XMLHttpRequestEventTarget.zig"),
@import("../webapi/net/XMLHttpRequestUpload.zig"),
diff --git a/src/browser/tests/canvas/canvas_rendering_context_2d.html b/src/browser/tests/canvas/canvas_rendering_context_2d.html
index 060ca6c86..f48d98586 100644
--- a/src/browser/tests/canvas/canvas_rendering_context_2d.html
+++ b/src/browser/tests/canvas/canvas_rendering_context_2d.html
@@ -171,3 +171,72 @@
testing.expectEqual(undefined, ctx.drawImage(src, 0, 0, 10, 10, 0, 0, 10, 10));
}
</script>
+
+<script id=CanvasRenderingContext2D#measureText>
+{
+ const ctx = document.createElement("canvas").getContext("2d");
+ testing.expectEqual("10px sans-serif", ctx.font);
+ let m = ctx.measureText("ab");
+ testing.expectEqual(true, m instanceof TextMetrics);
+ testing.expectEqual(12, m.width);
+
+ ctx.font = "bold 20px Arial";
+ testing.expectEqual("bold 20px Arial", ctx.font);
+ m = ctx.measureText("hello");
+ testing.expectEqual(60, m.width);
+ testing.expectEqual(16, m.actualBoundingBoxAscent);
+ testing.expectEqual(4, m.actualBoundingBoxDescent);
+ testing.expectEqual(60, m.actualBoundingBoxRight);
+ testing.expectEqual(0, m.actualBoundingBoxLeft);
+ testing.expectEqual(0, ctx.measureText("").width);
+
+ // Invalid font strings are ignored.
+ ctx.font = "bold";
+ testing.expectEqual("bold 20px Arial", ctx.font);
+ ctx.font = "12pt serif";
+ testing.expectEqual(16 * 0.6 * 3, ctx.measureText("abc").width);
+}
+</script>
+
+<script id=CanvasRenderingContext2D#noops>
+{
+ const ctx = document.createElement("canvas").getContext("2d");
+ ctx.setLineDash([4, 2]);
+ testing.expectEqual("4,2", ctx.getLineDash().join());
+ ctx.setLineDash([3]);
+ testing.expectEqual("3,3", ctx.getLineDash().join());
+ ctx.setLineDash([-1]);
+ testing.expectEqual("3,3", ctx.getLineDash().join());
+ ctx.setLineDash([]);
+ testing.expectEqual(0, ctx.getLineDash().length);
+ ctx.lineDashOffset = 2;
+ testing.expectEqual(2, ctx.lineDashOffset);
+
+ ctx.roundRect(0, 0, 10, 10, 2);
+ ctx.roundRect(0, 0, 10, 10, [1, 2]);
+ ctx.ellipse(5, 5, 4, 3, 0, 0, Math.PI * 2);
+ testing.expectEqual(false, ctx.isPointInPath(1, 1));
+ testing.expectEqual(false, ctx.isPointInStroke(1, 1));
+
+ const gradient = ctx.createLinearGradient(0, 0, 10, 0);
+ testing.expectEqual(true, gradient instanceof CanvasGradient);
+ gradient.addColorStop(0, "red");
+ gradient.addColorStop(1, "blue");
+ testing.expectError("IndexSizeError", () => gradient.addColorStop(2, "red"));
+ testing.expectEqual(true, ctx.createRadialGradient(0, 0, 1, 0, 0, 5) instanceof CanvasGradient);
+ testing.expectEqual(true, ctx.createConicGradient(0, 5, 5) instanceof CanvasGradient);
+ ctx.fillStyle = gradient;
+ ctx.strokeStyle = gradient;
+ ctx.fillRect(0, 0, 10, 10);
+
+ const pattern = ctx.createPattern(document.createElement("canvas"), "repeat");
+ testing.expectEqual(true, pattern instanceof CanvasPattern);
+ pattern.setTransform();
+ testing.expectError("SyntaxError", () => ctx.createPattern(document.createElement("canvas"), "sideways"));
+
+ testing.expectEqual(0, ctx.shadowBlur);
+ testing.expectEqual("none", ctx.filter);
+ ctx.shadowColor = "red";
+ testing.expectEqual("red", ctx.shadowColor);
+}
+</script>
diff --git a/src/browser/tests/canvas/offscreen_canvas.html b/src/browser/tests/canvas/offscreen_canvas.html
index 24c1277fe..3c3fc2765 100644
--- a/src/browser/tests/canvas/offscreen_canvas.html
+++ b/src/browser/tests/canvas/offscreen_canvas.html
@@ -96,3 +96,14 @@
testing.expectError('Index or size', () => ctx.getImageData(0, 0, 10, -5));
}
</script>
+
+<script id=OffscreenCanvasRenderingContext2D#measureText>
+{
+ const ctx = new OffscreenCanvas(10, 10).getContext("2d");
+ ctx.font = "16px sans-serif";
+ testing.expectEqual(48, ctx.measureText("hello").width);
+ ctx.setLineDash([1, 2]);
+ testing.expectEqual("1,2", ctx.getLineDash().join());
+ testing.expectEqual(true, ctx.createLinearGradient(0, 0, 1, 1) instanceof CanvasGradient);
+}
+</script>
diff --git a/src/browser/webapi/canvas/CanvasGradient.zig b/src/browser/webapi/canvas/CanvasGradient.zig
new file mode 100644
index 000000000..2f68e075d
--- /dev/null
+++ b/src/browser/webapi/canvas/CanvasGradient.zig
@@ -0,0 +1,49 @@
+// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+const std = @import("std");
+
+const js = @import("../../js/js.zig");
+
+const Execution = js.Execution;
+
+/// Nothing is painted, so a gradient only has to exist and accept stops.
+const CanvasGradient = @This();
+
+_stops: u32 = 0,
+
+pub fn init(exec: *const Execution) !*CanvasGradient {
+ return exec._factory.create(CanvasGradient{});
+}
+
+pub fn addColorStop(self: *CanvasGradient, offset: f64, _: []const u8) !void {
+ if (!(offset >= 0 and offset <= 1)) return error.IndexSizeError;
+ self._stops += 1;
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(CanvasGradient);
+
+ pub const Meta = struct {
+ pub const name = "CanvasGradient";
+ pub const prototype_chain = bridge.prototypeChain();
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const addColorStop = bridge.function(CanvasGradient.addColorStop, .{});
+};
diff --git a/src/browser/webapi/canvas/CanvasPattern.zig b/src/browser/webapi/canvas/CanvasPattern.zig
new file mode 100644
index 000000000..79664c720
--- /dev/null
+++ b/src/browser/webapi/canvas/CanvasPattern.zig
@@ -0,0 +1,44 @@
+// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+const js = @import("../../js/js.zig");
+
+const Execution = js.Execution;
+
+/// Nothing is painted, so a pattern only has to exist.
+const CanvasPattern = @This();
+
+_repetition: []const u8,
+
+pub fn init(repetition: []const u8, exec: *const Execution) !*CanvasPattern {
+ return exec._factory.create(CanvasPattern{ ._repetition = repetition });
+}
+
+pub fn setTransform(_: *const CanvasPattern, _: ?js.Value) void {}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(CanvasPattern);
+
+ pub const Meta = struct {
+ pub const name = "CanvasPattern";
+ pub const prototype_chain = bridge.prototypeChain();
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const setTransform = bridge.function(CanvasPattern.setTransform, .{ .noop = true });
+};
diff --git a/src/browser/webapi/canvas/CanvasRenderingContext2D.zig b/src/browser/webapi/canvas/CanvasRenderingContext2D.zig
index 7183d7733..ef9329e9c 100644
--- a/src/browser/webapi/canvas/CanvasRenderingContext2D.zig
+++ b/src/browser/webapi/canvas/CanvasRenderingContext2D.zig
@@ -24,6 +24,10 @@ const color = @import("../../color.zig");
const Canvas = @import("../element/html/Canvas.zig");
const ImageData = @import("../ImageData.zig");
+const context2d = @import("context2d.zig");
+const TextMetrics = @import("TextMetrics.zig");
+const CanvasGradient = @import("CanvasGradient.zig");
+const CanvasPattern = @import("CanvasPattern.zig");
const Execution = js.Execution;
@@ -37,6 +41,7 @@ _canvas: *Canvas,
/// Fill color.
/// TODO: Add support for `CanvasGradient` and `CanvasPattern`.
_fill_style: color.RGBA = color.RGBA.Named.black,
+_state: context2d.State = .{},
pub fn getCanvas(self: *const CanvasRenderingContext2D) *Canvas {
return self._canvas;
@@ -101,6 +106,56 @@ pub fn getImageData(
return ImageData.init(@intCast(sw), @intCast(sh), null, exec);
}
+pub fn getFont(self: *const CanvasRenderingContext2D) []const u8 {
+ return self._state.font;
+}
+
+pub fn setFont(self: *CanvasRenderingContext2D, value: []const u8, exec: *const Execution) !void {
+ return self._state.setFont(value, exec);
+}
+
+pub fn measureText(self: *const CanvasRenderingContext2D, text: []const u8, exec: *const Execution) !*TextMetrics {
+ return self._state.measureText(text, exec);
+}
+
+pub fn setLineDash(self: *CanvasRenderingContext2D, segments: []const f64, exec: *const Execution) !void {
+ return self._state.setLineDash(segments, exec);
+}
+
+pub fn getLineDash(self: *const CanvasRenderingContext2D) []const f64 {
+ return self._state.line_dash;
+}
+
+pub fn roundRect(_: *CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: ?js.Value) void {}
+pub fn ellipse(_: *CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64, _: ?bool) void {}
+pub fn isPointInPath(_: *const CanvasRenderingContext2D, _: js.Value, _: ?js.Value, _: ?js.Value, _: ?js.Value) bool {
+ return false;
+}
+pub fn isPointInStroke(_: *const CanvasRenderingContext2D, _: js.Value, _: ?js.Value, _: ?js.Value) bool {
+ return false;
+}
+
+pub fn createLinearGradient(_: *const CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, exec: *const Execution) !*CanvasGradient {
+ return CanvasGradient.init(exec);
+}
+
+pub fn createRadialGradient(_: *const CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64, exec: *const Execution) !*CanvasGradient {
+ return CanvasGradient.init(exec);
+}
+
+pub fn createConicGradient(_: *const CanvasRenderingContext2D, _: f64, _: f64, _: f64, exec: *const Execution) !*CanvasGradient {
+ return CanvasGradient.init(exec);
+}
+
+pub fn createPattern(_: *const CanvasRenderingContext2D, _: js.Value, repetition_: ?[]const u8, exec: *const Execution) !*CanvasPattern {
+ const repetition = repetition_ orelse "repeat";
+ const known = [_][]const u8{ "", "repeat", "repeat-x", "repeat-y", "no-repeat" };
+ for (known) |k| {
+ if (std.mem.eql(u8, repetition, k)) return CanvasPattern.init(k, exec);
+ }
+ return error.SyntaxError;
+}
+
pub fn save(_: *CanvasRenderingContext2D) void {}
pub fn restore(_: *CanvasRenderingContext2D) void {}
pub fn scale(_: *CanvasRenderingContext2D, _: f64, _: f64) void {}
@@ -139,7 +194,30 @@ pub const JsApi = struct {
};
pub const canvas = bridge.accessor(CanvasRenderingContext2D.getCanvas, null, .{});
- pub const font = bridge.property("10px sans-serif", .{ .template = false, .readonly = false });
+ pub const font = bridge.accessor(CanvasRenderingContext2D.getFont, CanvasRenderingContext2D.setFont, .{});
+ pub const measureText = bridge.function(CanvasRenderingContext2D.measureText, .{});
+ pub const setLineDash = bridge.function(CanvasRenderingContext2D.setLineDash, .{});
+ pub const getLineDash = bridge.function(CanvasRenderingContext2D.getLineDash, .{});
+ pub const lineDashOffset = bridge.property(0.0, .{ .template = false, .readonly = false });
+ pub const roundRect = bridge.function(CanvasRenderingContext2D.roundRect, .{ .noop = true });
+ pub const ellipse = bridge.function(CanvasRenderingContext2D.ellipse, .{ .noop = true });
+ pub const isPointInPath = bridge.function(CanvasRenderingContext2D.isPointInPath, .{});
+ pub const isPointInStroke = bridge.function(CanvasRenderingContext2D.isPointInStroke, .{});
+ pub const createLinearGradient = bridge.function(CanvasRenderingContext2D.createLinearGradient, .{});
+ pub const createRadialGradient = bridge.function(CanvasRenderingContext2D.createRadialGradient, .{});
+ pub const createConicGradient = bridge.function(CanvasRenderingContext2D.createConicGradient, .{});
+ pub const createPattern = bridge.function(CanvasRenderingContext2D.createPattern, .{});
+ pub const shadowBlur = bridge.property(0.0, .{ .template = false, .readonly = false });
+ pub const shadowColor = bridge.property("rgba(0, 0, 0, 0)", .{ .template = false, .readonly = false });
+ pub const shadowOffsetX = bridge.property(0.0, .{ .template = false, .readonly = false });
+ pub const shadowOffsetY = bridge.property(0.0, .{ .template = false, .readonly = false });
+ pub const filter = bridge.property("none", .{ .template = false, .readonly = false });
+ pub const imageSmoothingEnabled = bridge.property(true, .{ .template = false, .readonly = false });
+ pub const imageSmoothingQuality = bridge.property("low", .{ .template = false, .readonly = false });
+ pub const direction = bridge.property("ltr", .{ .template = false, .readonly = false });
+ pub const letterSpacing = bridge.property("0px", .{ .template = false, .readonly = false });
+ pub const wordSpacing = bridge.property("0px", .{ .template = false, .readonly = false });
+ pub const fontKerning = bridge.property("auto", .{ .template = false, .readonly = false });
pub const globalAlpha = bridge.property(1.0, .{ .template = false, .readonly = false });
pub const globalCompositeOperation = bridge.property("source-over", .{ .template = false, .readonly = false });
pub const strokeStyle = bridge.property("#000000", .{ .template = false, .readonly = false });
@@ -184,6 +262,10 @@ pub const JsApi = struct {
};
const testing = @import("../../../testing.zig");
+test {
+ _ = context2d;
+}
+
test "WebApi: CanvasRenderingContext2D" {
try testing.htmlRunner("canvas/canvas_rendering_context_2d.html", .{});
}
diff --git a/src/browser/webapi/canvas/OffscreenCanvasRenderingContext2D.zig b/src/browser/webapi/canvas/OffscreenCanvasRenderingContext2D.zig
index d7e2bd2e3..2048fdd27 100644
--- a/src/browser/webapi/canvas/OffscreenCanvasRenderingContext2D.zig
+++ b/src/browser/webapi/canvas/OffscreenCanvasRenderingContext2D.zig
@@ -22,6 +22,10 @@ const js = @import("../../js/js.zig");
const color = @import("../../color.zig");
const ImageData = @import("../ImageData.zig");
+const context2d = @import("context2d.zig");
+const TextMetrics = @import("TextMetrics.zig");
+const CanvasGradient = @import("CanvasGradient.zig");
+const CanvasPattern = @import("CanvasPattern.zig");
const Execution = js.Execution;
@@ -32,6 +36,7 @@ const OffscreenCanvasRenderingContext2D = @This();
/// Fill color.
/// TODO: Add support for `CanvasGradient` and `CanvasPattern`.
_fill_style: color.RGBA = color.RGBA.Named.black,
+_state: context2d.State = .{},
pub fn getFillStyle(self: *const OffscreenCanvasRenderingContext2D, exec: *Execution) ![]const u8 {
var w = std.Io.Writer.Allocating.init(exec.local_arena);
@@ -88,6 +93,56 @@ pub fn getImageData(
return ImageData.init(@intCast(sw), @intCast(sh), null, exec);
}
+pub fn getFont(self: *const OffscreenCanvasRenderingContext2D) []const u8 {
+ return self._state.font;
+}
+
+pub fn setFont(self: *OffscreenCanvasRenderingContext2D, value: []const u8, exec: *const Execution) !void {
+ return self._state.setFont(value, exec);
+}
+
+pub fn measureText(self: *const OffscreenCanvasRenderingContext2D, text: []const u8, exec: *const Execution) !*TextMetrics {
+ return self._state.measureText(text, exec);
+}
+
+pub fn setLineDash(self: *OffscreenCanvasRenderingContext2D, segments: []const f64, exec: *const Execution) !void {
+ return self._state.setLineDash(segments, exec);
+}
+
+pub fn getLineDash(self: *const OffscreenCanvasRenderingContext2D) []const f64 {
+ return self._state.line_dash;
+}
+
+pub fn roundRect(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: ?js.Value) void {}
+pub fn ellipse(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64, _: ?bool) void {}
+pub fn isPointInPath(_: *const OffscreenCanvasRenderingContext2D, _: js.Value, _: ?js.Value, _: ?js.Value, _: ?js.Value) bool {
+ return false;
+}
+pub fn isPointInStroke(_: *const OffscreenCanvasRenderingContext2D, _: js.Value, _: ?js.Value, _: ?js.Value) bool {
+ return false;
+}
+
+pub fn createLinearGradient(_: *const OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, exec: *const Execution) !*CanvasGradient {
+ return CanvasGradient.init(exec);
+}
+
+pub fn createRadialGradient(_: *const OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64, exec: *const Execution) !*CanvasGradient {
+ return CanvasGradient.init(exec);
+}
+
+pub fn createConicGradient(_: *const OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, exec: *const Execution) !*CanvasGradient {
+ return CanvasGradient.init(exec);
+}
+
+pub fn createPattern(_: *const OffscreenCanvasRenderingContext2D, _: js.Value, repetition_: ?[]const u8, exec: *const Execution) !*CanvasPattern {
+ const repetition = repetition_ orelse "repeat";
+ const known = [_][]const u8{ "", "repeat", "repeat-x", "repeat-y", "no-repeat" };
+ for (known) |k| {
+ if (std.mem.eql(u8, repetition, k)) return CanvasPattern.init(k, exec);
+ }
+ return error.SyntaxError;
+}
+
pub fn save(_: *OffscreenCanvasRenderingContext2D) void {}
pub fn restore(_: *OffscreenCanvasRenderingContext2D) void {}
pub fn scale(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64) void {}
@@ -125,7 +180,30 @@ pub const JsApi = struct {
pub var class_id: bridge.ClassId = undefined;
};
- pub const font = bridge.property("10px sans-serif", .{ .template = false, .readonly = false });
+ pub const font = bridge.accessor(OffscreenCanvasRenderingContext2D.getFont, OffscreenCanvasRenderingContext2D.setFont, .{});
+ pub const measureText = bridge.function(OffscreenCanvasRenderingContext2D.measureText, .{});
+ pub const setLineDash = bridge.function(OffscreenCanvasRenderingContext2D.setLineDash, .{});
+ pub const getLineDash = bridge.function(OffscreenCanvasRenderingContext2D.getLineDash, .{});
+ pub const lineDashOffset = bridge.property(0.0, .{ .template = false, .readonly = false });
+ pub const roundRect = bridge.function(OffscreenCanvasRenderingContext2D.roundRect, .{ .noop = true });
+ pub const ellipse = bridge.function(OffscreenCanvasRenderingContext2D.ellipse, .{ .noop = true });
+ pub const isPointInPath = bridge.function(OffscreenCanvasRenderingContext2D.isPointInPath, .{});
+ pub const isPointInStroke = bridge.function(OffscreenCanvasRenderingContext2D.isPointInStroke, .{});
+ pub const createLinearGradient = bridge.function(OffscreenCanvasRenderingContext2D.createLinearGradient, .{});
+ pub const createRadialGradient = bridge.function(OffscreenCanvasRenderingContext2D.createRadialGradient, .{});
+ pub const createConicGradient = bridge.function(OffscreenCanvasRenderingContext2D.createConicGradient, .{});
+ pub const createPattern = bridge.function(OffscreenCanvasRenderingContext2D.createPattern, .{});
+ pub const shadowBlur = bridge.property(0.0, .{ .template = false, .readonly = false });
+ pub const shadowColor = bridge.property("rgba(0, 0, 0, 0)", .{ .template = false, .readonly = false });
+ pub const shadowOffsetX = bridge.property(0.0, .{ .template = false, .readonly = false });
+ pub const shadowOffsetY = bridge.property(0.0, .{ .template = false, .readonly = false });
+ pub const filter = bridge.property("none", .{ .template = false, .readonly = false });
+ pub const imageSmoothingEnabled = bridge.property(true, .{ .template = false, .readonly = false });
+ pub const imageSmoothingQuality = bridge.property("low", .{ .template = false, .readonly = false });
+ pub const direction = bridge.property("ltr", .{ .template = false, .readonly = false });
+ pub const letterSpacing = bridge.property("0px", .{ .template = false, .readonly = false });
+ pub const wordSpacing = bridge.property("0px", .{ .template = false, .readonly = false });
+ pub const fontKerning = bridge.property("auto", .{ .template = false, .readonly = false });
pub const globalAlpha = bridge.property(1.0, .{ .template = false, .readonly = false });
pub const globalCompositeOperation = bridge.property("source-over", .{ .template = false, .readonly = false });
pub const strokeStyle = bridge.property("#000000", .{ .template = false, .readonly = false });
diff --git a/src/browser/webapi/canvas/TextMetrics.zig b/src/browser/webapi/canvas/TextMetrics.zig
new file mode 100644
index 000000000..9538a8510
--- /dev/null
+++ b/src/browser/webapi/canvas/TextMetrics.zig
@@ -0,0 +1,76 @@
+// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+const js = @import("../../js/js.zig");
+
+const Execution = js.Execution;
+
+/// Metrics from the deterministic text model in text_measure.zig: ascent is
+/// 0.8em and descent 0.2em, as in a generic sans-serif face.
+const TextMetrics = @This();
+
+_width: f64,
+_ascent: f64,
+_descent: f64,
+
+pub fn init(width: f64, font_size: f64, exec: *const Execution) !*TextMetrics {
+ return exec._factory.create(TextMetrics{
+ ._width = width,
+ ._ascent = font_size * 0.8,
+ ._descent = font_size * 0.2,
+ });
+}
+
+pub fn getWidth(self: *const TextMetrics) f64 {
+ return self._width;
+}
+
+pub fn getAscent(self: *const TextMetrics) f64 {
+ return self._ascent;
+}
+
+pub fn getDescent(self: *const TextMetrics) f64 {
+ return self._descent;
+}
+
+pub fn getIdeographicBaseline(self: *const TextMetrics) f64 {
+ return -self._descent;
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(TextMetrics);
+
+ pub const Meta = struct {
+ pub const name = "TextMetrics";
+ pub const prototype_chain = bridge.prototypeChain();
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const width = bridge.accessor(TextMetrics.getWidth, null, .{});
+ pub const actualBoundingBoxLeft = bridge.property(0.0, .{ .template = false });
+ pub const actualBoundingBoxRight = bridge.accessor(TextMetrics.getWidth, null, .{});
+ pub const actualBoundingBoxAscent = bridge.accessor(TextMetrics.getAscent, null, .{});
+ pub const actualBoundingBoxDescent = bridge.accessor(TextMetrics.getDescent, null, .{});
+ pub const fontBoundingBoxAscent = bridge.accessor(TextMetrics.getAscent, null, .{});
+ pub const fontBoundingBoxDescent = bridge.accessor(TextMetrics.getDescent, null, .{});
+ pub const emHeightAscent = bridge.accessor(TextMetrics.getAscent, null, .{});
+ pub const emHeightDescent = bridge.accessor(TextMetrics.getDescent, null, .{});
+ pub const hangingBaseline = bridge.accessor(TextMetrics.getAscent, null, .{});
+ pub const alphabeticBaseline = bridge.property(0.0, .{ .template = false });
+ pub const ideographicBaseline = bridge.accessor(TextMetrics.getIdeographicBaseline, null, .{});
+};
diff --git a/src/browser/webapi/canvas/context2d.zig b/src/browser/webapi/canvas/context2d.zig
new file mode 100644
index 000000000..02e06b787
--- /dev/null
+++ b/src/browser/webapi/canvas/context2d.zig
@@ -0,0 +1,97 @@
+// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+//! State and behaviour shared by the on-screen and offscreen 2D contexts.
+
+const std = @import("std");
+
+const js = @import("../../js/js.zig");
+const text_measure = @import("../../text_measure.zig");
+const TextMetrics = @import("TextMetrics.zig");
+
+const Execution = js.Execution;
+
+pub const default_font = "10px sans-serif";
+
+pub const State = struct {
+ font: []const u8 = default_font,
+ font_size: f64 = 10,
+ line_dash: []const f64 = &.{},
+
+ /// Invalid font strings are ignored, per the spec.
+ pub fn setFont(self: *State, value: []const u8, exec: *const Execution) !void {
+ if (std.mem.eql(u8, value, self.font)) return;
+ const size = parseFontSize(value) orelse return;
+ self.font = try exec.arena.dupe(u8, value);
+ self.font_size = size;
+ }
+
+ pub fn measureText(self: *const State, text: []const u8, exec: *const Execution) !*TextMetrics {
+ return TextMetrics.init(text_measure.width(text, self.font_size), self.font_size, exec);
+ }
+
+ /// Negative or non-finite segments leave the list unchanged; an odd count
+ /// is repeated, per the spec.
+ pub fn setLineDash(self: *State, segments: []const f64, exec: *const Execution) !void {
+ for (segments) |s| {
+ if (!(s >= 0) or std.math.isInf(s)) return;
+ }
+ if (std.mem.eql(f64, segments, self.line_dash)) return;
+ if (segments.len % 2 == 0) {
+ self.line_dash = try exec.arena.dupe(f64, segments);
+ return;
+ }
+ const doubled = try exec.arena.alloc(f64, segments.len * 2);
+ @memcpy(doubled[0..segments.len], segments);
+ @memcpy(doubled[segments.len..], segments);
+ self.line_dash = doubled;
+ }
+};
+
+/// The size in px out of a CSS font shorthand, or null when there is none.
+fn parseFontSize(font: []const u8) ?f64 {
+ var it = std.mem.tokenizeAny(u8, font, " \t\n\r");
+ while (it.next()) |raw| {
+ // "16px/1.5" carries a line-height.
+ const token = raw[0 .. std.mem.indexOfScalar(u8, raw, '/') orelse raw.len];
+ const units = [_]struct { suffix: []const u8, px: f64 }{
+ .{ .suffix = "px", .px = 1 },
+ .{ .suffix = "pt", .px = 4.0 / 3.0 },
+ .{ .suffix = "rem", .px = 16 },
+ .{ .suffix = "em", .px = 16 },
+ .{ .suffix = "%", .px = 0.16 },
+ };
+ for (units) |unit| {
+ if (!std.ascii.endsWithIgnoreCase(token, unit.suffix)) continue;
+ const number = std.fmt.parseFloat(f64, token[0 .. token.len - unit.suffix.len]) catch continue;
+ if (number < 0 or std.math.isInf(number) or std.math.isNan(number)) return null;
+ return number * unit.px;
+ }
+ }
+ return null;
+}
+
+const testing = std.testing;
+test "context2d: parseFontSize" {
+ try testing.expectEqual(10, parseFontSize("10px sans-serif").?);
+ try testing.expectEqual(20, parseFontSize("italic bold 20px/1.5 Arial, sans-serif").?);
+ try testing.expectEqual(16, parseFontSize("12pt serif").?);
+ try testing.expectEqual(24, parseFontSize("1.5em serif").?);
+ try testing.expectEqual(null, parseFontSize("bold serif"));
+ try testing.expectEqual(null, parseFontSize(""));
+}