Canvas size and WebGL - Web APIs 编辑

Effect of canvas size on rendering with WebGL

{{IncludeSubnav("/en-US/Learn")}}

This WebGL example explores the effect of setting (or not setting) the canvas size to its element size in CSS pixels, as it appears in the browser window.

With scissor() and clear() we can demonstrate how the WebGL drawing buffer is affected by the size of the canvas.

The size of the first canvas is set to the styled Element size, determined by CSS. This is done by assigning the width and height properties of the canvas to the values of the clientWidth and clientHeight properties, respectively.

In contrast, no such assignment is done for the second canvas. The internal width and height properties of the canvas remain at default values, which are different than the actual size of the canvas Element in the browser window.

The effect is clearly visible when using scissor() and clear() to draw a square in the center of the canvas, by specifying its position and size in pixels. In the first canvas, we get the desired result. In the second, the square has the wrong shape, size, and position.

<p>Compare the two canvases.</p>
<canvas>Your browser does not seem to support
    HTML5 canvas.</canvas>
<canvas>Your browser does not seem to support
    HTML5 canvas.</canvas>
body {
  text-align : center;
}
canvas {
  display : inline-block;
  width : 120px;
  height : 80px;
  margin : auto;
  padding : 0;
  border : none;
  background-color : black;
}
window.addEventListener("load", function() {
  "use strict"
  var firstCanvas = document.getElementsByTagName("canvas")[0],
    secondCanvas = document.getElementsByTagName("canvas")[1];
  firstCanvas.width = firstCanvas.clientWidth;
  firstCanvas.height = firstCanvas.clientHeight;
  [firstCanvas, secondCanvas].forEach(function(canvas) {
    var gl = canvas.getContext("webgl")
      || canvas.getContext("experimental-webgl");
    if (!gl) {
      document.querySelector("p").innerHTML =
        "Failed to get WebGL context. "
        + "Your browser or device may not support WebGL.";
      return;
    }
    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);
  });
}, false);

The source code of this example is also available on GitHub.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:46 次

字数:4806

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文