Blazor .NET 8, game loops and fast canvas drawing using JSImport and JSExport

timelapse photography of car lights
Photo by Kelly on Pexels.com

Just a quick one today, another Blazor and .NET post. A fair while ago I built a basic game framework for Blazor using .NET 7 (see this repo here). That reminds me, I really should update it to use .NET 8.

However, I’d used the old (now deprecated) undocumented Blazor JavaScript functions to improve the speed of the interop between JS and Blazor, since obviously when gaming you want fast framerates right? 🫡

person lying on bed covering white blanket
Photo by Pixabay on Pexels.com

However, I never got around to migrating the code to use the new JSImport and JSExport attributes introduced in .NET 7 due to my laziness.

Anyway, I figured better late than never, so I recently put together a small tester project to compare the speed of the vanilla JS interop to the new replacement for the ‘unmarshalled’ code I was using. There nothing really scientifically accurate going on here, just a test of drawing a load of very small rectangles. However, its clear from just looking at both that the new replacement for the deprecated unmarshalled code works much faster… One small problem though…

a man looking at the paper while holding a coffee and phone
Photo by Mikhail Nilov on Pexels.com

I did identify one small hiccup though, as the new collocation feature for keeping JS files next to the components doesn’t work with JSHost.ImportAsync which you need when using JSImport and JSExport attributes (see the issue I logged about this here, it seems due to this they’re going to hopefully update the documentation to make this limitation clear). Due to this, I had to move the JS file into the ‘wwwroot’ folder instead when its in the Razor class library, but its not the end of the world. Apart from that, all went smoothly…

Anyway, if you’re interested, check out the repo here…