From b48a0db0403f84dd9ed118ab2a92b451472c79f9 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Tue, 13 Dec 2022 21:46:33 -0800 Subject: [PATCH] font: web canvas rect sprite func --- src/font/sprite/canvas.zig | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/src/font/sprite/canvas.zig b/src/font/sprite/canvas.zig index 00654f96d..8499eb038 100644 --- a/src/font/sprite/canvas.zig +++ b/src/font/sprite/canvas.zig @@ -59,6 +59,8 @@ pub const Trapezoid = struct { /// We only use alpha-channel so a pixel can only be "on" or "off". pub const Color = enum(u8) { + const CSS_BUF_MAX = 24; + on = 255, off = 0, _, @@ -72,6 +74,12 @@ pub const Color = enum(u8) { const scaled = @floatToInt(u16, (unscaled * max_u16) / max); return .{ .red = 0, .green = 0, .blue = 0, .alpha = scaled }; } + + fn cssColor(self: Color, buf: []u8) ![]u8 { + return try std.fmt.bufPrint(buf, "rgba(0, 0, 0, {:.2})", .{ + @intToFloat(f32, @enumToInt(self)) / 255, + }); + } }; /// Composition operations that are supported. @@ -121,9 +129,14 @@ const WebCanvasImpl = struct { } pub fn rect(self: *WebCanvasImpl, v: Rect, color: Color) void { - _ = self; - _ = v; - _ = color; + const ctx = self.context(color) catch return; + defer ctx.deinit(); + ctx.call(void, "fillRect", .{ + @intCast(u32, v.x), + @intCast(u32, v.y), + v.width, + v.height, + }) catch return; } pub fn trapezoid(self: *WebCanvasImpl, t: Trapezoid) void { @@ -149,6 +162,20 @@ const WebCanvasImpl = struct { _ = dest; } + fn context(self: WebCanvasImpl, fill: ?Color) !js.Object { + const ctx = try self.canvas.call(js.Object, "getContext", .{js.string("2d")}); + errdefer ctx.deinit(); + + // Set our fill color + if (fill) |c| { + var buf: [Color.CSS_BUF_MAX]u8 = undefined; + const color = try c.cssColor(&buf); + try ctx.set("fillStyle", js.string(color)); + } + + return ctx; + } + pub fn writeAtlas(self: *WebCanvasImpl, alloc: Allocator, atlas: *font.Atlas) !font.Atlas.Region { _ = self; _ = alloc;