功能检测 WebGL
在第一个示例中,我们将检查浏览器是否支持 WebGL。为此,我们将尝试从 canvas 元素获取 WebGL 渲染上下文。 WebGL 渲染上下文是一个接口,通过它可以设置和查询图形机器的状态、将数据发送到 WebGL 以及执行绘制命令。
在单个上下文接口中保存图形机器的状态并非 WebGL 所独有。其他图形 API,例如 canvas 2D 渲染上下文,也这样做。但是,您可以调整的属性和变量对于每个 API 都是不同的。
html
<p>[ Here would go the result of WebGL feature detection ]</p>
<button>Press here to detect WebGLRenderingContext</button>
css
body {
text-align: center;
}
button {
display: block;
font-size: inherit;
margin: auto;
padding: 0.6em;
}
js
const paragraph = document.querySelector("p");
const button = document.querySelector("button");
// Adding click event handler to button.
button.addEventListener("click", detectWebGLContext);
function detectWebGLContext() {
// Create canvas element. The canvas is not added to the
// document itself, so it is never displayed in the
// browser window.
const canvas = document.createElement("canvas");
// Get WebGLRenderingContext from canvas element.
const gl = canvas.getContext("webgl");
// Report the result.
paragraph.textContent =
gl instanceof WebGLRenderingContext
? "Congratulations! Your browser supports WebGL."
: "Failed. Your browser or device may not support WebGL.";
}
此示例的源代码也可在 GitHub 上找到。