Canvas 大小和 WebGL

此 WebGL 示例將探討在瀏覽器視窗中看到的 CSS 畫素中,將 canvas 的大小設定為其元素大小(或不設定)的效果。

Canvas 大小對 WebGL 渲染的影響

透過 scissor()clear(),我們可以演示 WebGL 繪圖緩衝區如何受到 canvas 大小的影響。

第一個 canvas 的大小設定為由 CSS 決定的樣式化 Element 大小。這是透過分別將 canvas 的 widthheight 屬性賦值給 clientWidthclientHeight 屬性的值來實現的。

相比之下,第二個 canvas 沒有進行此類賦值。canvas 的內部 widthheight 屬性保持預設值,這與瀏覽器視窗中 canvas Element 的實際大小不同。

透過指定畫素位置和大小,使用 scissor()clear() 在 canvas 中心繪製一個正方形時,效果清晰可見。在第一個 canvas 中,我們得到了期望的結果。在第二個 canvas 中,正方形的形狀、大小和位置都不正確。

html
<p>Compare the two canvases.</p>
<canvas>Your browser does not seem to support HTML canvas.</canvas>
<canvas>Your browser does not seem to support HTML canvas.</canvas>
css
body {
  text-align: center;
}
canvas {
  display: inline-block;
  width: 120px;
  height: 80px;
  margin: auto;
  padding: 0;
  border: none;
  background-color: black;
}
js
const [firstCanvas, secondCanvas] = document.getElementsByTagName("canvas");
firstCanvas.width = firstCanvas.clientWidth;
firstCanvas.height = firstCanvas.clientHeight;
[firstCanvas, secondCanvas].forEach((canvas) => {
  const gl = canvas.getContext("webgl");
  gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  gl.enable(gl.SCISSOR_TEST);
  gl.scissor(30, 10, 60, 60);
  gl.clearColor(1.0, 1.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
});

此示例的原始碼也可在 GitHub 上找到。