How to colour an intersected area?

(Apologise for my bad English)
Hello, I would like to ask how to colour an overlapping or intersecting area with a complex shape? Like this


I figured out maybe screen-reading shaders (I found this on docs) useful because it can colour the screen, but I just not smart enough to how to used it.
Sorry if it was a dumb question, because I am noob in this shader. And I’ll thankful if you would like to help me!

I think I found a solution, which make the alpha of the sprite or object low and when overlapped, it will result on substituted alpha (combined) and we can use this. First, we use SubViewport and not using screen_texture, then put the sprite under the SubViewport, and then put the ColorRect (or any image) that will to give the colour to this intersecting , which is like

<Node2d
<<SubViewport
<<<Sprite2D
<<<Sprite2D2
<<<other sprite…
<<ColorRect

Then in SubViewport set Transparent bg to true, then set alpha for these 2 sprite to maybe half like 128.

Now attach the shader for the ColorRect:

shader_type canvas_item;

uniform sampler2D viewport_texture;

void fragment() {
    vec4 viewport_color = texture(viewport_texture, UV);
    //If two transparent sprite overlap, the intersected area have substituted alpha, so we can check
    if (viewport_color.a > 0.6) {
        // Color the intersection (By invert it)
        viewport_color.rgb = vec3(1.0) - viewport_color.rgb;
    }
    COLOR = viewport_color;
}

The viewport texture can be set by $ColorRect.material.set_shader_parameter("viewport_texture", $SubViewport.get_texture()). Done, now just put those two sprite close together and you get the result.

Why use Transparent bg? Because if not then it won’t working and the texture would think everything is opaque

Why not use the main viewport and edit the global background color alpha to 0?


I don’t exactly know why, it give me infinite mirror if I use main viewport (Maybe using COLOR = viewport_color cause this recursive effect), so I use SubViewport instead