Alpha blend

I found that I couldn’t find a suitable transparent blending algorithm, so I made one by myself.

The core part of this shader is the following function. You can copy and use it.

vec4 alpha_blend(vec4 o,vec4 n){
	float sum = n.a + o.a;
	sum = clamp(sum,0.0001,1.0);
	float rate = n.a / sum;
	vec4 res = mix(o,n,rate);
	res.a = clamp(n.a+o.a,0.0,1.0);
	return res;
}

 

Shader code
shader_type canvas_item;

uniform sampler2D pic;

vec4 alpha_blend(vec4 o,vec4 n){
	float sum = n.a + o.a;
	sum = clamp(sum,0.0001,1.0);
	float rate = n.a / sum;
	vec4 res = mix(o,n,rate);
	res.a = clamp(n.a+o.a,0.0,1.0);
	return res;
}


void fragment() {
	COLOR = alpha_blend(COLOR,texture(pic,mod(UV,1.0)));
}

Tags
alpha blend
The shader code and all code snippets in this post are under MIT license and can be used freely. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

Related shaders

2D Drop Shadow using alpha

Fog of war with alpha cut off as white color

Alpha Separate VisualShaderNode 4.4

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments