Smooth outline 2D

A shader for outline, with smoothness to fade out edges. Also an option for having the shader pulse over time.

Shader code
shader_type canvas_item;
render_mode unshaded;

uniform bool Smooth = true;
uniform float width : hint_range(0.0, 64) = 1.0;
uniform vec4 outline_color : hint_color = vec4(0.0, 0.0, 0.0, 1.0);
uniform int pixel_size : hint_range(1, 10) = 4;
uniform float width_speed :hint_range(0.1, 10) = 1;

void fragment()
{
    float _width = width + ((sin(TIME*width_speed) + 1f) -2f) * 10f;
    vec2 unit = (1.0/float(pixel_size) ) / vec2(textureSize(TEXTURE, 0));
    vec4 pixel_color = texture(TEXTURE, UV);
    if (pixel_color.a == 0.0) {
        pixel_color = outline_color;
        pixel_color.a = 0.0;
        for (float x = -ceil(_width); x <= ceil(_width); x++) {
            for (float y = -ceil(_width); y <= ceil(_width); y++) {
                if (texture(TEXTURE, UV + vec2(x*unit.x, y*unit.y)).a == 0.0 || (x==0.0 && y==0.0)) {
                    continue;
                }
                if (Smooth) {
                    pixel_color.a += outline_color.a / (pow(x,2)+pow(y,2)) * (1.0-pow(2.0, -_width));
                    if (pixel_color.a > 1.0) {
                        pixel_color.a = 1.0;
                    }
                } else {
                    pixel_color.a = outline_color.a;
                    return
                }
            }
        }
    }
    COLOR = pixel_color;
}
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from Tanders

Wiggle 2D

Related shaders

Smooth Radial Gradient

2D Outline and Rainbow outline 2 in 1

Colorful Outline

guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
zkmark
zkmark
20 days ago

The line is not drawn on the outside edges of the image.
Can you add a margin? For example this one has the option to add margin
https://godotshaders.com/shader/2d-outline-inline/

adictonator
adictonator
1 day ago

this is not working at all in Godot 3.5