在WebGL中,将纹理贴到HTML画布上的最干净的方法是什么?我可以设置正交投影并渲染带纹理的四边形,但是否有更简洁的方法?
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform vec2 u_resolution;
varying vec2 v_texCoord;
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);
v_texCoord = a_texCoord;
}
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform vec2 u_offset;
uniform vec2 u_scale;
varying vec2 v_texCoord;
void main() {
gl_Position = vec4(a_position * u_scale + u_offset, 0, 1);
v_texCoord = a_texCoord;
}
最后,在任何一种情况下,您都可以使用3x3矩阵数学简化代码。
attribute vec2 a_position;
uniform mat3 u_matrix;
void main() {
// Multiply the position by the matrix.
gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1);
}
请设置矩阵。您可以使用单位正方形(添加比例矩阵以将其放大像素)或使用像素。
一个矩阵
[
2 / canvasWidth, 0, 0,
0, -2 / canvasHeight, 0,
-1, 1, 1
]
将像素转换为剪裁空间。一个矩阵的
[
imageWidth, 0, 0,
0, imageHeight, 0,
0, 0, 1
]