检测 WebGL 支持的正确方法?

问题描述 投票:0回答:8

我正在尝试跨多个浏览器检测 WebGL 支持,并且遇到了以下情况。当前版本的 Firefox 似乎使用以下检查来报告积极支持,即使访问者的视频卡被列入黑名单和/或 WebGL 被禁用:

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

我尝试指导我的用户使用以下步骤启用 WebGL。这在某些情况下有效,但并非总是如此。显然,这不是我可以向公众提出的要求:

  1. 在 Firefox 地址栏中输入 about:config
  2. 要启用 WebGL,请将 webgl.force-enabled 设置为 true

这促使我创建了自己的检测支持的方法,该方法使用 jQuery 注入画布元素来检测支持。这利用了我在各种 WebGL 库和插件中发现的许多技术。问题是,测试非常困难(非常感谢任何关于下面的链接是否适合您的评论!)。为了使这个问题成为一个客观的问题,我想知道是否有一种普遍接受的方法来检测所有浏览器的 WebGL 支持

测试网址:

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

javascript jquery firefox cross-browser webgl
8个回答
62
投票

优秀的 Three 库实际上有一种检测以下内容的机制:

  1. WebGL 支持
  2. 文件API支持
  3. 工人们的支持

特别是对于 WebGL,这里是使用的代码:

function webgl_support () { 
   try {
    var canvas = document.createElement('canvas'); 
    return !!window.WebGLRenderingContext &&
      (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
   } catch(e) {
     return false;
   }
 };

该代码片段是 Detector 类的一部分,该类还可能向用户显示相应的错误消息。


37
投票

[2014 年 10 月] 我更新了 Modernizrs 示例以匹配他们的 当前实现,这是来自 http://get.webgl.org/ 的清理版本。

Modernizr 确实如此,

var canvas;
var ctx;
var exts;

try {
  canvas = createElement('canvas');
  ctx = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  exts = ctx.getSupportedExtensions();
}
catch (e) {
  return;
}

if (ctx !== undefined) {
  Modernizr.webglextensions = new Boolean(true);
}

for (var i = -1, len = exts.length; ++i < len; ){
  Modernizr.webglextensions[exts[i]] = true;
}

canvas = undefined;

Chromium 指向 http://get.webgl.org/ 以获取规范支持实现,

try { gl = canvas.getContext("webgl"); }
catch (x) { gl = null; }

if (gl == null) {
    try { gl = canvas.getContext("experimental-webgl"); experimental = true; }
    catch (x) { gl = null; }
}

20
投票

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

所示

这是一个正确的 JavaScript 函数,用于检测 WebGL 支持,具有各种实验性 WebGL 上下文名称并检查特殊情况,例如通过 NoScript 或 TorBrowser 阻止 WebGL 函数。

它将报告三种 WebGL 功能状态之一:

  • WebGL 已启用 — 返回 TRUE,或返回
  • WebGL 对象,如果传递了第一个参数
  • WebGL 已禁用 — 返回 FALSE,您可以根据需要更改它>
  • WebGL 未实现 — 返回 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;
}

8
投票

除了@Andrew的回答之外,还有实验模式可以支持。我写了以下代码片段:

var canvasID = 'webgl',
    canvas = document.getElementById(canvasID),
    gl,
    glExperimental = false;

function hasWebGL() {

    try { gl = canvas.getContext("webgl"); }
    catch (x) { gl = null; }

    if (gl === null) {
        try { gl = canvas.getContext("experimental-webgl"); glExperimental = true; }
        catch (x) { gl = null; }
    }

    if(gl) { return true; }
    else if ("WebGLRenderingContext" in window) { return true; } // not a best way, as you're not 100% sure, so you can change it to false
    else { return false; }
}

根据您的ID更改

canvasID
变量。

在 Chrome、Safari、Firefox、Opera 和 IE(8 到 10)上进行了测试。如果是 Safari,请记住它是可用的,但您需要显式启用 WebGL(启用开发人员菜单,然后启用 Web GL 选项)。


2
投票

为了检测支持 WebGL 的浏览器,但排除旧版浏览器可能无法很好地支持它(根据 WebGL 检测为受支持但实际上不支持 中的需要,以排除 Android 4.4.2 设备),我添加了更严格但不相关的检查:

function hasWebGL() {
    var supported;

    try {
        var canvas = document.createElement('canvas');
        supported = !! window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
    } catch(e) { supported = false; }

    try {
        // let is by no means required, but will help us rule out some old browsers/devices with potentially buggy implementations: http://caniuse.com/#feat=let
        eval('let foo = 123;');
    } catch (e) { supported = false; }

    if (supported === false) {
        console.log("WebGL is not supported");
    }

    canvas = undefined;

    return supported;
},

1
投票
// this code will detect WebGL version until WebGL Version maxVersionTest 
var
maxVersionTest = 5,
canvas = document.createElement('canvas'),
webglVersion = (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')) ? 1 : null,
canvas = null; // free context

// range: if maxVersionTest = 5 makes [5, 4, 3, 2]
Array.apply(null, Array(maxVersionTest - 1))
.map(function (_, idx) {return idx + 2;})
.reverse()
.some(function(version){
    // cant reuse canvas, potential to exceed contexts or mem limit *
    if (document.createElement('canvas').getContext('webgl'+version))
        return !!(webglVersion = version);
});

console.log(webglVersion);

* 关于“超出上下文或内存限制的潜力”请参阅 https://bugs.chromium.org/p/chromium/issues/detail?id=226868


1
投票

来自MDN

// Run everything inside window load event handler, to make sure
// DOM is fully loaded and styled before trying to manipulate it.
window.addEventListener("load", function() {
  var paragraph = document.querySelector("p"),
    button = document.querySelector("button");
  // Adding click event handler to button.
  button.addEventListener("click", detectWebGLContext, false);
  function detectWebGLContext () {
    // Create canvas element. The canvas is not added to the
    // document itself, so it is never displayed in the
    // browser window.
    var canvas = document.createElement("canvas");
    // Get WebGLRenderingContext from canvas element.
    var gl = canvas.getContext("webgl")
      || canvas.getContext("experimental-webgl");
    // Report the result.
    if (gl && gl instanceof WebGLRenderingContext) {
      paragraph.innerHTML =
        "Congratulations! Your browser supports WebGL.";
    } else {
      paragraph.innerHTML = "Failed to get WebGL context. "
        + "Your browser or device may not support WebGL.";
    }
  }
}, false);
body {
  text-align : center;
}
button {
  display : block;
  font-size : inherit;
  margin : auto;
  padding : 0.6em;
}
<p>[ Here would go the result of WebGL feature detection ]</p>
<button>Press here to detect WebGLRenderingContext</button>


0
投票
// Check for WebGL support
function isWebGLSupported() {
    try {
        var canvas = document.createElement('canvas');
        return !!(
            window.WebGLRenderingContext &&
            (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))
        );
    } catch (e) {
        return false;
    }
}

// Example usage
if (isWebGLSupported()) {
    console.log('WebGL is supported in this browser!');
} else {
    console.log('WebGL is not supported in this browser.');
}
© www.soinside.com 2019 - 2024. All rights reserved.