DEV Community

Konrad Chmielecki
Konrad Chmielecki

Posted on • Edited on

3 1

webgl context, canvas and blazor pages

When I developed my simple game PolySnake, I decided to experimenting with Blazor. Creating port for server and webassembly don't took me too much time. But as usual, supporting different platform is tedious task.

Problem I had, is lose connection between gl context and canvas. This happen when page is changed. When switching pages is happening, html components from previous page are removed.

Return to previous page causes components to be creating agin. But for webGL is not thad same canvas.
And sadly webGL context it does not allow to by signed to other canvas.

For me initializing everything one more time is not good idea. This is not efficient and require heavy changes in architecture of my game.
And I started thinking, that I can creating canvas in javascript. This canvas will be alive that long as is required. And only need is attached that canvas to other component.

This component take focus and handling keyboard inputs. Now when page will be changed,
that same canvas will be reattach to proper place.

This is how it is looking in my code Index.razor and main.js

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay