Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Created April 5, 2014 17:54
Show Gist options
  • Save mattdesl/9995467 to your computer and use it in GitHub Desktop.
Save mattdesl/9995467 to your computer and use it in GitHub Desktop.
Simulating context loss with a mouse click
var loseCtx = context.gl.getExtension("WEBGL_lose_context");
//May not exist in some browsers, or if WebGLInspector is enabled
if (loseCtx) {
//Attach a mouse click to the canvas...
canvas.addEventListener("mousedown", function() {
//Force the canvas to lose its WebGL context
loseCtx.loseContext();
//Here you may want to present the user with a progress indicator
canvas.style.visibility = "hidden";
//Delay re-initialization just a bit.
setTimeout(function() {
canvas.style.visibility = "visible";
//Force the canvas to restore its context
loseCtx.restoreContext();
}, 1000);
}, false);
} else {
console.warn("Cannot simulate context loss");
}
@amitlzkpa
Copy link

What is context on line 1?

@amitlzkpa
Copy link

Nevermind, figured it out.
let context = renderer.getContext('webgl');

Here's my full context lost handling and simulation setup by adding callbacks to yours:

let renderer = new THREE.WebGLRenderer();
let context = renderer.getContext('webgl');


context.canvas.addEventListener("webglcontextlost", function(event) {
    event.preventDefault();
}, false);

context.canvas.addEventListener("webglcontextrestored", function(event) {
}, false);


var loseCtx = context.getExtension("WEBGL_lose_context");
//May not exist in some browsers, or if WebGLInspector is enabled
if (loseCtx) {
    //Attach a mouse click to the canvas...
    document.addEventListener("mousedown", function() {
    	console.log('Force lose ctxt');
        //Force the canvas to lose its WebGL context
        loseCtx.loseContext();

        //Here you may want to present the user with a progress indicator
        container.style.visibility = "hidden";

        //Delay re-initialization just a bit. 
        setTimeout(function() {
            container.style.visibility = "visible";

	    	console.log('Restore ctxt');
            //Force the canvas to restore its context
            loseCtx.restoreContext();
        }, 4000);
    }, false);
} else {
    console.warn("Cannot simulate context loss");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment