【问题标题】:Why is rendering blurred in WebGL?为什么在 WebGL 中渲染模糊?
【发布时间】:2019-07-13 13:39:02
【问题描述】:

我对 WebGL 很陌生。我尝试从 WebGL 教程 https://webglfundamentals.org/webgl/lessons/webgl-fundamentals.html 复制和粘贴代码以呈现随机大小和随机颜色的矩形,但发现矩形在我的浏览器 (Firefox 67.0.4) 中非常模糊。

我已经粘贴了下面的屏幕截图。因为下面的图像要小得多,所以模糊不像在我的浏览器中那样明显,但你仍然可以看到它是模糊的。

有谁知道为什么我的浏览器显示模糊,以及如何解决?

下面我重新粘贴了整个 WebGL 程序的代码:

<canvas id="canvas"></canvas>
<!-- vertex shader -->
<script id="2d-vertex-shader" type="x-shader/x-vertex">
attribute vec2 a_position;

uniform vec2 u_resolution;

void main() {
   // convert the rectangle from pixels to 0.0 to 1.0
   vec2 zeroToOne = a_position / u_resolution;

   // convert from 0->1 to 0->2
   vec2 zeroToTwo = zeroToOne * 2.0;

   // convert from 0->2 to -1->+1 (clipspace)
   vec2 clipSpace = zeroToTwo - 1.0;

   gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
}
</script>
<!-- fragment shader -->
<script id="2d-fragment-shader" type="x-shader/x-fragment">
precision mediump float;

uniform vec4 u_color;

void main() {
   gl_FragColor = u_color;
}
</script>

<script src="https://webglfundamentals.org/webgl/resources/webgl-utils.js"></script>

<script>
//MAIN JAVASCRIPT CODE FOLLOWS HERE

"use strict";

function main() {
  // Get A WebGL context
  /** @type {HTMLCanvasElement} */
  var canvas = document.getElementById("canvas");
  var gl = canvas.getContext("webgl");
  if (!gl) {
    return;
  }

  // setup GLSL program
  var program = webglUtils.createProgramFromScripts(gl, ["2d-vertex-shader", "2d-fragment-shader"]);

  // look up where the vertex data needs to go.
  var positionAttributeLocation = gl.getAttribLocation(program, "a_position");

  // look up uniform locations
  var resolutionUniformLocation = gl.getUniformLocation(program, "u_resolution");
  var colorUniformLocation = gl.getUniformLocation(program, "u_color");

  // Create a buffer to put three 2d clip space points in
  var positionBuffer = gl.createBuffer();

  // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

  webglUtils.resizeCanvasToDisplaySize(gl.canvas);

  // Tell WebGL how to convert from clip space to pixels
  gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

  // Clear the canvas
  gl.clearColor(0, 0, 0, 0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  // Tell it to use our program (pair of shaders)
  gl.useProgram(program);

  // Turn on the attribute
  gl.enableVertexAttribArray(positionAttributeLocation);

  // Bind the position buffer.
  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

  // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
  var size = 2;          // 2 components per iteration
  var type = gl.FLOAT;   // the data is 32bit floats
  var normalize = false; // don't normalize the data
  var stride = 0;        // 0 = move forward size * sizeof(type) each iteration to get the next position
  var offset = 0;        // start at the beginning of the buffer
  gl.vertexAttribPointer(
      positionAttributeLocation, size, type, normalize, stride, offset);

  // set the resolution
  gl.uniform2f(resolutionUniformLocation, gl.canvas.width, gl.canvas.height);

  // draw 50 random rectangles in random colors
  for (var ii = 0; ii < 50; ++ii) {
    // Setup a random rectangle
    // This will write to positionBuffer because
    // its the last thing we bound on the ARRAY_BUFFER
    // bind point
    setRectangle(
        gl, randomInt(300), randomInt(300), randomInt(300), randomInt(300));

    // Set a random color.
    gl.uniform4f(colorUniformLocation, Math.random(), Math.random(), Math.random(), 1);

    // Draw the rectangle.
    var primitiveType = gl.TRIANGLES;
    var offset = 0;
    var count = 6;
    gl.drawArrays(primitiveType, offset, count);
  }
}

// Returns a random integer from 0 to range - 1.
function randomInt(range) {
  return Math.floor(Math.random() * range);
}

// Fill the buffer with the values that define a rectangle.
function setRectangle(gl, x, y, width, height) {
  var x1 = x;
  var x2 = x + width;
  var y1 = y;
  var y2 = y + height;
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
     x1, y1,
     x2, y1,
     x1, y2,
     x1, y2,
     x2, y1,
     x2, y2,
  ]), gl.STATIC_DRAW);
}

main();

</script>

<style>
@import url("https://webglfundamentals.org/webgl/resources/webgl-tutorials.css");
body {
  margin: 0;
}
canvas {
  width: 100vw;
  height: 100vh;
  display: block;
}
</style>

【问题讨论】:

标签: webgl


【解决方案1】:

原因是因为您将样式部分放在最后。事情是按顺序执行的,所以脚本首先执行。当时没有样式所以画布是默认的300x150。脚本绘制。然后&lt;style&gt; 部分出现并告诉浏览器以窗口的全尺寸显示该 300x150 纹理。将样式部分移到脚本之前,最好是移到顶部。

该示例仍然只渲染一次。如果您调整页面大小,它不会重新呈现,因此即使您将 &lt;style&gt; 移动到 &lt;script&gt; 上方,如果窗口开始很小并且您将窗口大小调整为较大,您仍然会变得模糊。

要处理大小调整,您需要再次渲染矩形。要绘制相同的矩形,您需要保存使用的位置、大小和颜色。由您决定它们是否应该相对于窗口保持相同的大小,是否保持相同的方面。

您可能会发现this article 很有用。

下面的代码随机选取 50 个矩形和颜色

  // pick 50 random rectangles and their colors
  const rectangles = [];
  for (let ii = 0; ii < 50; ++ii) {
    rectangles.push({
      rect: [randomInt(300), randomInt(300), randomInt(300), randomInt(300)],
      color: [Math.random(), Math.random(), Math.random(), 1],
    });
  }

然后它在渲染函数中绘制之前选择的矩形

function render() {
     ...

    for (const rectangle of rectangles) {
      // This will write to positionBuffer because
      // its the last thing we bound on the ARRAY_BUFFER
      // bind point
      setRectangle(
          gl, ...rectangle.rect);

      // Set the color.
      gl.uniform4f(colorUniformLocation, ...rectangle.color);

      // Draw the rectangle.
      var primitiveType = gl.TRIANGLES;
      var offset = 0;
      var count = 6;
      gl.drawArrays(primitiveType, offset, count);
    }
}

当页面调整大小时,它最终会调用render

window.addEventListener('resize', render);

"use strict";

function main() {
  // Get A WebGL context
  /** @type {HTMLCanvasElement} */
  var canvas = document.getElementById("canvas");
  var gl = canvas.getContext("webgl");
  if (!gl) {
    return;
  }

  // setup GLSL program
  var program = webglUtils.createProgramFromScripts(gl, ["2d-vertex-shader", "2d-fragment-shader"]);

  // look up where the vertex data needs to go.
  var positionAttributeLocation = gl.getAttribLocation(program, "a_position");

  // look up uniform locations
  var resolutionUniformLocation = gl.getUniformLocation(program, "u_resolution");
  var colorUniformLocation = gl.getUniformLocation(program, "u_color");

  // Create a buffer to put three 2d clip space points in
  var positionBuffer = gl.createBuffer();

  // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

  // pick 50 random rectangles and their colors
  const rectangles = [];
  for (let ii = 0; ii < 50; ++ii) {
    rectangles.push({
      rect: [randomInt(300), randomInt(300), randomInt(300), randomInt(300)],
      color: [Math.random(), Math.random(), Math.random(), 1],
    });
  }

  function render() { 
    webglUtils.resizeCanvasToDisplaySize(gl.canvas);

    // Tell WebGL how to convert from clip space to pixels
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    // Clear the canvas
    gl.clearColor(0, 0, 0, 0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    // Tell it to use our program (pair of shaders)
    gl.useProgram(program);

    // Turn on the attribute
    gl.enableVertexAttribArray(positionAttributeLocation);

    // Bind the position buffer.
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

    // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
    var size = 2;          // 2 components per iteration
    var type = gl.FLOAT;   // the data is 32bit floats
    var normalize = false; // don't normalize the data
    var stride = 0;        // 0 = move forward size * sizeof(type) each iteration to get the next position
    var offset = 0;        // start at the beginning of the buffer
    gl.vertexAttribPointer(
        positionAttributeLocation, size, type, normalize, stride, offset);

    // set the resolution
    gl.uniform2f(resolutionUniformLocation, gl.canvas.width, gl.canvas.height);

    for (const rectangle of rectangles) {
      // This will write to positionBuffer because
      // its the last thing we bound on the ARRAY_BUFFER
      // bind point
      setRectangle(
          gl, ...rectangle.rect);

      // Set the color.
      gl.uniform4f(colorUniformLocation, ...rectangle.color);

      // Draw the rectangle.
      var primitiveType = gl.TRIANGLES;
      var offset = 0;
      var count = 6;
      gl.drawArrays(primitiveType, offset, count);
    }
  }
  render();
  window.addEventListener('resize', render);
}

// Returns a random integer from 0 to range - 1.
function randomInt(range) {
  return Math.floor(Math.random() * range);
}

// Fill the buffer with the values that define a rectangle.
function setRectangle(gl, x, y, width, height) {
  var x1 = x;
  var x2 = x + width;
  var y1 = y;
  var y2 = y + height;
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
     x1, y1,
     x2, y1,
     x1, y2,
     x1, y2,
     x2, y1,
     x2, y2,
  ]), gl.STATIC_DRAW);
}

main();
body {
  margin: 0;
}
canvas {
  width: 100vw;
  height: 100vh;
  display: block;
}
<canvas id="canvas"></canvas>
<!-- vertex shader -->
<script id="2d-vertex-shader" type="x-shader/x-vertex">
attribute vec2 a_position;

uniform vec2 u_resolution;

void main() {
   // convert the rectangle from pixels to 0.0 to 1.0
   vec2 zeroToOne = a_position / u_resolution;

   // convert from 0->1 to 0->2
   vec2 zeroToTwo = zeroToOne * 2.0;

   // convert from 0->2 to -1->+1 (clipspace)
   vec2 clipSpace = zeroToTwo - 1.0;

   gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
}
</script>
<!-- fragment shader -->
<script id="2d-fragment-shader" type="x-shader/x-fragment">
precision mediump float;

uniform vec4 u_color;

void main() {
   gl_FragColor = u_color;
}
</script>
<script src="https://webglfundamentals.org/webgl/resources/webgl-utils.js"></script>

【讨论】:

  • 不应该这段代码处理大小以确保画布的大小适合视口吗? webglUtils.resizeCanvasToDisplaySize(gl.canvas); gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  • 只有一次(您问题中的代码,而不是此答案中的代码)。您问题页面中的代码仅绘制一次。之后它再也不会被绘制,所以如果你从一个小窗口开始并调整到一个大窗口,除非你刷新页面,否则它会变得模糊。每次调整页面窗口大小时,答案中的示例都会重新渲染。
  • 非常感谢您的澄清,但请注意我从未调整过我的窗口大小。它在第一次渲染时变得模糊,没有任何调整大小。
  • 请注意,@gman,我赞成您的答案,因为它非常有帮助,但我暂时取消选中答案,因为我仍然无法弄清楚为什么我会变得模糊。我将画布大小设置为 100% 并在渲染之前最大化浏览器,并且从未调整浏览器大小,但仍然变得模糊。
  • 抱歉,已修复答案
猜你喜欢
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 2015-03-11
  • 2013-05-14
  • 1970-01-01
  • 2011-09-14
  • 2014-01-23
  • 1970-01-01
相关资源
最近更新 更多