From c615cece40d4f21fa59e33bbe2d008bc907fd2db Mon Sep 17 00:00:00 2001 From: Asger Finding Date: Mon, 19 Oct 2026 02:30:22 +0200 Subject: [PATCH] Remove the WebGL context loss listeners in Game#destroy --- CHANGELOG.md | 10 ++++++++++ src/core/Game.js | 25 +++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cf2f2d57..282b9a143 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Change Log +## Unreleased + +### Bug Fixes + +- Fixed an error when the WebGL context of a destroyed game was lost. + +### Thanks + +@asger-finding + ## Version 2.20.2 - 20 February 2025 ### Bug Fixes diff --git a/src/core/Game.js b/src/core/Game.js index f00e08cc9..5688d8e41 100644 --- a/src/core/Game.js +++ b/src/core/Game.js @@ -496,6 +496,18 @@ Phaser.Game = function (width, height, renderer, parent, state, transparent, ant */ this._nextFpsNotification = 0; + /** + * @property {function} _onContextLost - Internal event handler reference. + * @private + */ + this._onContextLost = null; + + /** + * @property {function} _onContextRestored - Internal event handler reference. + * @private + */ + this._onContextRestored = null; + // Parse the configuration object (if any) if (arguments.length === 1 && typeof arguments[0] === 'object') { @@ -913,8 +925,10 @@ Phaser.Game.prototype = { this.renderer = new PIXI.WebGLRenderer(this, this.config); this.renderType = Phaser.WEBGL; this.context = null; - this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); - this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); + this._onContextLost = this.contextLost.bind(this); + this._onContextRestored = this.contextRestored.bind(this); + this.canvas.addEventListener('webglcontextlost', this._onContextLost, false); + this.canvas.addEventListener('webglcontextrestored', this._onContextRestored, false); } catch (webGLRendererError) { @@ -1272,6 +1286,13 @@ Phaser.Game.prototype = { this.physics.destroy(); this.plugins.destroy(); this.tweens.destroy(); + + if (this._onContextLost) + { + this.canvas.removeEventListener('webglcontextlost', this._onContextLost, false); + this.canvas.removeEventListener('webglcontextrestored', this._onContextRestored, false); + } + this.renderer.destroy(false); Phaser.Canvas.removeFromDOM(this.canvas);