@@ -29,6 +29,9 @@ const OffscreenCanvas = @import("../../canvas/OffscreenCanvas.zig");
2929
3030const Canvas = @This ();
3131_proto : * HtmlElement ,
32+ _cached : ? DrawingContext = null ,
33+
34+ const ContextType = enum { none , @"2d" , webgl };
3235
3336pub fn asElement (self : * Canvas ) * Element {
3437 return self ._proto ._proto ;
@@ -68,17 +71,28 @@ const DrawingContext = union(enum) {
6871};
6972
7073pub fn getContext (self : * Canvas , context_type : []const u8 , page : * Page ) ! ? DrawingContext {
71- if (std .mem .eql (u8 , context_type , "2d" )) {
72- const ctx = try page ._factory .create (CanvasRenderingContext2D { ._canvas = self });
73- return .{ .@"2d" = ctx };
74- }
75-
76- if (std .mem .eql (u8 , context_type , "webgl" ) or std .mem .eql (u8 , context_type , "experimental-webgl" )) {
77- const ctx = try page ._factory .create (WebGLRenderingContext {});
78- return .{ .webgl = ctx };
74+ if (self ._cached ) | cached | {
75+ const matches = switch (cached ) {
76+ .@"2d" = > std .mem .eql (u8 , context_type , "2d" ),
77+ .webgl = > std .mem .eql (u8 , context_type , "webgl" ) or std .mem .eql (u8 , context_type , "experimental-webgl" ),
78+ };
79+ return if (matches ) cached else null ;
7980 }
8081
81- return null ;
82+ const drawing_context : DrawingContext = blk : {
83+ if (std .mem .eql (u8 , context_type , "2d" )) {
84+ const ctx = try page ._factory .create (CanvasRenderingContext2D { ._canvas = self });
85+ break :blk .{ .@"2d" = ctx };
86+ }
87+
88+ if (std .mem .eql (u8 , context_type , "webgl" ) or std .mem .eql (u8 , context_type , "experimental-webgl" )) {
89+ const ctx = try page ._factory .create (WebGLRenderingContext {});
90+ break :blk .{ .webgl = ctx };
91+ }
92+ return null ;
93+ };
94+ self ._cached = drawing_context ;
95+ return drawing_context ;
8296}
8397
8498/// Transfers control of the canvas to an OffscreenCanvas.
0 commit comments