WebGL full screen button using HTML and JavaScript?

Viewed 399

WebGL full screen button using HTML and JavaScript?

I have searched this topic up many times, and could not find something that would work, however I did find a button that works for putting my page in full screen

<input type="button" value="click to toggle fullscreen" onclick="toggleFullScreen()">
<script>function toggleFullScreen() {
  if ((document.fullScreenElement && document.fullScreenElement !== null) ||    
   (!document.mozFullScreen && !document.webkitIsFullScreen)) {
    if (document.documentElement.requestFullScreen) {  
      document.documentElement.requestFullScreen();  
    } else if (document.documentElement.mozRequestFullScreen) {  
      document.documentElement.mozRequestFullScreen();  
    } else if (document.documentElement.webkitRequestFullScreen) {  
      document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);  
    }  
  } else {  
    if (document.cancelFullScreen) {  
      document.cancelFullScreen();  
    } else if (document.mozCancelFullScreen) {  
      document.mozCancelFullScreen();  
    } else if (document.webkitCancelFullScreen) {  
      document.webkitCancelFullScreen();  
    }  
  }  
}</script>

This does work, but not for WebGL content. Here is my iframe that I use for loading WebGL content on my site.

<!DOCTYPE html>
<html>
<body>
<iframe src="WEBGL CONTENT IS HERE"></iframe>
</body>
</html>

If anyone could help that would be great!

2 Answers

Have you tried calling requestFullscreen to the iframe element?

I just wrote this quick test and it works:

<div>
<iframe src="https://bbc.com"></iframe>
</div>
<button onclick="toggle()">Make that iframe full screen</button>

<script>
  function toggle() {
    document.querySelector('iframe').requestFullscreen();
  }
</script>

Hope this solves your issue.

Here is a Better Way to do this that work across all browser including safari also

Create a Function that make window full screen

const fullScreen = (invoker) => {
  const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement;

  if (!fullscreenElement) {

    if (invoker.requestFullscreen) { invoker.requestFullscreen() }
    else if (invoker.webkitRequestFullscreen) { invoker.webkitRequestFullscreen() }
         
  } else {
    
    if (document.exitFullscreen) { document.exitFullscreen() }
    else if (document.webkitExitFullscreen) { document.webkitExitFullscreen()}
  }

}

Now You can call on any event listener

const webgl = document.querySelector("canvas.webgl");

webgl.addEventListener('dblclick', () => {
  // calling our fullscreen function here webgl is invoker
  fullScreen(webgl);
})
Related