我正在开发一个小程序,用于通过 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/