检查客户端浏览器是否支持和启用 WebGL2

Check if WebGL2 is supported and enabled in client's browser

我想检查用户浏览器是否启用并支持 WebGL 2。

有很多关于 WebGL 1 的帖子,但我没有找到任何与 WebGL 版本 2 相关的帖子。

检查 webgl2 上下文是否在 canvas 元素上可用,如下所示:

const isWebGL2Supported = () => !!document.createElement('canvas').getContext('webgl2')

isWebGL2Supported() ? console.log('supported') : console.log('unsupported')

您应该检查的方式只是查看尝试获取 webgl2 上下文是成功还是失败

const gl = document.createElement('canvas').getContext('webgl2');
if (!gl) {
  console.log('your browser/OS/drivers do not support WebGL2');
} else {
  console.log('webgl2 works!');
}
  

你也可以通过查看window.WebGL2RenderingContext是否存在来猜测是浏览器不支持WebGL2还是用户的OS/GPU/Drivers。

const gl = document.createElement('canvas').getContext('webgl2');
if (!gl) {
  if (typeof WebGL2RenderingContext !== 'undefined') {
    console.log('your browser appears to support WebGL2 but it might be disabled. Try updating your OS and/or video card drivers');
  } else {
    console.log('your browser has no WebGL2 support at all'); 
  }
} else {
  console.log('webgl2 works!');
}