skip to Main Content

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?

2

Answers


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

    Login or Signup to reply.
  2. 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.
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search