Proper way to detect WebGL support?

2019-01-07 17:42发布

I am attempting to detect WebGL support across multiple browsers and I've encountered the following scenario. The current version of Firefox appears to report positive support using the following check, even when the visitor's video card is black-listed and/or WebGL is disabled:

if (window.WebGLRenderingContext) {
    // This is true in Firefox under certain circumstances,
    // even when WebGL is disabled...
}

I've tried instructing my users to enable WebGL using the following steps. This has worked in some cases, but not always. Obviously, this is not something I can request of the general public:

  1. Type about:config in Firefox’s address bar
  2. To enable WebGL, set webgl.force-enabled to true

This has led me to create my own method for detecting support, which uses jQuery to inject a canvas element to detect support. This pulls on a number of techniques I found in various WebGL libraries and plugins. The trouble is, it is extremely difficult to test (any comments on whether the link below works for you are much appreciated!). To make this an objective question, I would like to know if there's a universally accepted way to detect WebGL support across all browsers.

TEST URL:

http://jsfiddle.net/Jn49q/5/

7条回答
欢心
2楼-- · 2019-01-07 18:21

As seen in http://www.browserleaks.com/webgl#howto-detect-webgl

This is a proper javascript function to detect WebGL support, with all kind of experimental WebGL context names and with checking of special cases, such as blocking WebGL functions by NoScript or TorBrowser.

It will report one of the three WebGL capability states:

  • WebGL is enabled — return TRUE, or return
  • WebGL object, if the first argument was passed
  • WebGL is disabled — return FALSE, you can change it if you need>
  • WebGL is not implimented — return FALSE
function webgl_detect(return_context)
{
    if (!!window.WebGLRenderingContext) {
        var canvas = document.createElement("canvas"),
             names = ["webgl2", "webgl", "experimental-webgl", "moz-webgl", "webkit-3d"],
           context = false;

        for(var i=0;i< names.length;i++) {
            try {
                context = canvas.getContext(names[i]);
                if (context && typeof context.getParameter == "function") {
                    // WebGL is enabled
                    if (return_context) {
                        // return WebGL object if the function's argument is present
                        return {name:names[i], gl:context};
                    }
                    // else, return just true
                    return true;
                }
            } catch(e) {}
        }

        // WebGL is supported, but disabled
        return false;
    }

    // WebGL not supported
    return false;
}
查看更多
登录 后发表回答