In the Babylon.js framework, when utilizing the
getContext function on an HTMLCanvas element, it creates a new rendering context object, such as
experimental-webgl, to facilitate 3D rendering. This context creation is essential for the engine to operate effectively, and it occurs during the setup of the private
_gl property within the
ThinEngine class, which serves as the foundation for the Engine.
However, there’s an issue we’ve identified: the
webgl context created in this process is never released, even when the engine is disposed of. Consequently, for applications that rely on creating and destroying multiple engines, not necessarily in the order of their creation, various canvas contexts may linger in the browser for each engine instance. Over time, this could lead to an overflow of
webgl contexts, with the browser eventually discarding the oldest context in its creation history. Depending on the application, this behavior might deviate from the expected workflow and pose challenges for debugging, particularly for developers less familiar with the HTML Canvas API.
Our proposal is to address this issue by exposing a public method on the
ThinEngine class for explicitly releasing the current canvas WebGL context, if it exists. This enhancement would empower developers to efficiently manage memory and perform a straightforward cleanup of the context as needed.
We have considered incorporating this context cleanup method as part of the
dispose function’s internal calls. However, this approach may not align with the preferred workflow for some applications that might have manually created the context before initializing the engine. Making it a private method within
dispose could also introduce breaking changes for existing users.
Hence, our preferred solution is to introduce a separate public method, as mentioned earlier. This approach maintains flexibility for those who may want to persist manually created contexts while providing a clean solution for memory management.
We believe that this feature would not only benefit the application we are currently working on but also be a valuable addition for the wider Babylon.js community. Therefore, we are interested in creating a Pull Request (PR) to implement this feature, as it has the potential to streamline context management and enhance the Babylon.js experience for developers.
Your feedback and insights on this proposal are highly appreciated, and we look forward to collaborating on this enhancement.
Thank you for considering this feature request.