樣板程式碼 1

此示例描述了從現在開始將隱藏的重複程式碼片段,以及定義一個使 WebGL 初始化更容易的 JavaScript 實用程式函式。

設定 WebGL 渲染上下文的樣板程式碼

到目前為止,您已經很習慣於看到重複的 HTMLCSSJavaScript 程式碼片段。因此,我們從現在開始將隱藏它們。這將使我們能夠專注於與學習 WebGL 最相關的有趣程式碼片段。

具體來說,HTML 有一個包含頁面描述性文字的 <p> 元素,它也可能包含錯誤訊息;一個 <canvas> 元素;以及一個可選的 <button>。CSS 包含針對 bodycanvasbutton 的規則。任何額外的非平凡 CSS 和 HTML 將顯示在具體示例的頁面上。

在後續示例中,我們將使用一個 JavaScript 幫助函式 getRenderingContext() 來初始化 WebGL 渲染上下文。到目前為止,您應該能夠理解該函式的作用。基本上,它從 canvas 元素獲取 WebGL 渲染上下文,初始化繪圖緩衝區,將其清空為黑色,並返回初始化後的上下文。如果出現錯誤,它會顯示一條錯誤訊息並返回 null

最後,所有 JavaScript 程式碼都將在一個立即函式中執行,這是一種常見的 JavaScript 技術(請參閱 函式)。函式的宣告和呼叫也將被隱藏。

HTML

html
<p>[ Some descriptive text about the example. ]</p>
<button>[ Optional button element. ]</button>
<canvas>Your browser does not seem to support HTML canvas.</canvas>

CSS

css
body {
  text-align: center;
}
canvas {
  display: block;
  width: 280px;
  height: 210px;
  margin: auto;
  padding: 0;
  border: none;
  background-color: black;
}
button {
  display: block;
  font-size: inherit;
  margin: auto;
  padding: 0.6em;
}

JavaScript

js
function getRenderingContext() {
  const canvas = document.querySelector("canvas");
  canvas.width = canvas.clientWidth;
  canvas.height = canvas.clientHeight;
  const gl =
    canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
  if (!gl) {
    const paragraph = document.querySelector("p");
    paragraph.textContent =
      "Failed to get WebGL context. Your browser or device may not support WebGL.";
    return null;
  }
  gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  return gl;
}

此示例的原始碼也可在 GitHub 上獲取。