如何修改此 WebGL drawImage 等效项,使其不会清除在透明图像下绘制的像素?



我按照本教程为 WebGL 重新创建drawImage,但它没有涵盖的一件事是,对于具有透明像素的图像,例如游戏精灵,图像矩形后面的所有内容(即使像素是透明的(都会被清除。

这可能是微不足道的,但我对 GLSL 完全陌生,以下是着色器:

fragment

precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D u_texture;
void main() {
gl_FragColor = texture2D(u_texture, v_texcoord);
}

vertex

attribute vec4 a_position;
attribute vec2 a_texcoord;
uniform mat4 u_matrix;
varying vec2 v_texcoord;
void main() {
gl_Position = u_matrix * a_position;
v_texcoord = a_texcoord;
}

如何修改这些像素以避免在将精灵的透明像素渲染到它们上时隐藏已经渲染的帧中的像素?

我想通了。对于初学者来说很难找到,因为入门教程没有解释很多重要的基础知识,例如您可以使用texture2D(u_texture, v_texcoord).a来获取 alpha 的事实,或者discard不绘制像素的事实。

precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D u_texture;
void main() {
vec4 color = texture2D(u_texture, v_texcoord);
float alpha = texture2D(u_texture, v_texcoord).a;
if (alpha < 1.0) {
discard;
}
gl_FragColor = color;
}

最新更新