功能檢測 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 上找到。