Stopping an animationRequestFrame loop if the canvas is removed from the Dom context?

I figured this was going to be a no brainer… but for some reason Im struggling.

So lets say I have an HTML canvas element that has a basic animationRequestFrame loop going on it:

public render() {
        this.context.clearColor(0, 0, 0, 1)
        this.context.clear(this.context.COLOR_BUFFER_BIT)
        this._bindUniforms()    
        this._bindAttributes()       
        this.context.bindBuffer(this.context.ELEMENT_ARRAY_BUFFER, this._indexBuffer)
        this.context.drawElements(this.context.TRIANGLES, 6, this.context.UNSIGNED_SHORT, 0)
        requestAnimationFrame(this.render.bind(this))
    }

I thought if I deleted the canvas element from the DOM context that the renderloop would not be able to do its thing. But then I realized that is not the case because you can do off screen canvas rendering.

Lets say without having access to a dispose method what would be the best way for the rendering loop to just detect that the element is no longer on the page and not call the next render frame?

I’m probably going to have to hold a reference to each render that I have on the page and create a destroy or dispose function for the render huh?

This is just webGL not BJS btw. Im trying to cook something up but well see how it goes.

Can’t you use cancelAnimationFrame to cancel the current RAF?

Yes, but I also mean to release all the resources as well and guess I did not specify that in the question XD.

After some research it looks like this:

context.getExtension('WEBGL_lose_context')?.loseContext();

plus a cancel of the loop should do the trick! Thanks.

1 Like