javascript - Sprite 的拉伸(stretch)与 Canvas 尺寸成反比

标签 javascript glsl webgl shader vertex-shader

我正在开发一个小程序,用于通过 2D 变换渲染 Sprite ,链接 here 。我的问题是我试图渲染一个 100px x 100px 的正方形,但它被拉伸(stretch)成一个矩形。我对有问题的代码是什么一无所知,但这里有一些相关的部分。

const position = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, position)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  -w/2,  h/2,
   w/2,  h/2,
  -w/2, -h/2,
   w/2, -h/2
]), gl.STATIC_DRAW)

 

gl.bindBuffer(gl.ARRAY_BUFFER, position)
gl.vertexAttribPointer(attrib.vertexPosition,
                      2, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(attrib.vertex)

 

gl.uniformMatrix2fv(uniform.transformMatrix, false, transform)
gl.uniform2f(uniform.translation, x+w/2, y+h/2)
gl.uniform2f(uniform.screenRes, gl.canvas.width, gl.canvas.height)

顶点着色器:

attribute vec2 aVertexPosition;
attribute vec2 aTextureCoord;

uniform mat2 uTransformMatrix;
uniform vec2 uTranslation;
uniform vec2 uScreenRes;

varying vec2 vTextureCoord;

void main() {
  gl_Position = vec4(2.0 * (uTransformMatrix * aVertexPosition + uTranslation) / uScreenRes - 1.0, 1.0, 1.0);
  vTextureCoord = aTextureCoord;
}

随意调整笔中的变量,尤其是 Canvas 尺寸;当您缩小尺寸时, Sprite 的该尺寸也会放大,反之亦然。

附注我不关心纹理如何反转。我把它搁置起来以供稍后使用。

最佳答案

您的代码是正确的,但是您忘记指定视口(viewport)。 在进行任何绘制调用之前添加此内容(在您的情况下,最好在 gl.clear() 之后)

gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)

The WebGLRenderingContext.viewport() method of the WebGL API sets the viewport, which specifies the affine transformation of x and y from normalized device coordinates to window coordinates.

关于javascript - Sprite 的拉伸(stretch)与 Canvas 尺寸成反比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52561970/

相关文章:

javascript - Node.JS Socket.IO 将数据包发送到特定的连接 ID

javascript - Visual Studio 2010 中 Javascript 中的区域/代码折叠

c++ - 着色器存储 block 与统一 block

javascript - 添加到 YouTube 的 Canvas 不可见

javascript - Vue JS - 如何让 WebGL 通过 Vue 渲染而不消失?

javascript - 如何使用 javascript 根据单元格的值更改单元格的背景颜色?

javascript - 如何使用队列的 Promise 对不同的函数调用进行排序

java - libGDX - TextButton 字体的自定义着色器

c++ - 错误修复。 OpenGL、GLSL Sprite 网格渲染问题

GLSL 除法与乘法