0

I have a page showing WebGL animation and the animation could be changed.

As the animation should be changed, I remove the old canvas and then create a new canvas to perform the new animation:

let canvasElem = null

const deleteCanvas = () => {
    canvasElem.width = 0
    canvasElem.height = 0
    canvasContainer.removeChild(canvasElem)
    canvasElem = null
}

const newAnimation = () => {
    deleteCanvas()
    
    // create new canvas for the new WebGL animation
    canvasElem = document.createElement('canvas')
    canvasContainer.appendChild(canvasElem)

    // init WebGL animation on new canvas
    initWebGLAnimation(canvasElem)
}

After calling newAnimation() several times (likely 15 times), the error shows:

There are too many active WebGL contexts on this page, the oldest context will be lost.

It's so weird, I did remove all the old canvases right?

How can I remove all the contexts of old canvases that no longer in use?

VaJoy Larn
  • 113
  • 13
  • Does this answer your question? [How to free and garbage collect a WebGL context?](https://stackoverflow.com/questions/37072303/how-to-free-and-garbage-collect-a-webgl-context) – gre_gor Mar 03 '23 at 14:55
  • Don't delete the canvas, clear the webgl context. canvas.getContext('webgl').clear(); – mrall Mar 03 '23 at 18:28

2 Answers2

0

You could try and scope the canvasElem variable locally, inside newAnimation().

PedroSantana
  • 86
  • 1
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 08 '23 at 08:37
0

A reference to each canvas context remains, perhaps due to whatever the initWebGLAnimation method is doing. Instead of creating new canvases, clear the webgl context.

let canvasElem = null; let canvasContext = null;

const clearCanvas = () => {
    canvasElem.width = 0; canvasElem.height = 0;
    if(canvasContext) canvasContext.clear();
}
const newAnimation = () => {

    if(!canvasElem) {
        canvasElem = document.createElement('canvas');
        canvasContext = canvasElem.getContext('webgl');
        canvasContainer.appendChild(canvasElem);
    }
    clearCanvas();

    // init WebGL animation on canvas
    // canvasContext = 
    initWebGLAnimation(canvasElem); //ideally this method should return some kind of reference to the webgl context.
}
mrall
  • 140
  • 4