Distance from the fragment to camera is always dependent to the position of the camera. It is just impossible to make value constant if it is not a constant.
I'd advise you to rework the requirements for what you are developing. You have to clarify for yourself what depth you need, it seems that it doesn't rely on camera position.
I would advise you to think about introducing a plane, that would be a reference for calculating the depth. Parameters, that specifying position of the plane in space can be passed to the shader as uniforms.
How to calculate the distance from a point to the plain? The depth can be calculated as the length of a perpendicular to plane dropped from a fragment. Let's we have a arbitrary point p that lays on the plane and a normal n to that plane.
The distance would be:
d = dot(f, n) - dot(p, n)
where f - the position of the fragment.
A simple shader that does this calculation is listed below:
uniform vec3 u_point;
uniform vec3 u_normal;
uniform float u_unitLength;
varying vec4 v_worldPosition;
void main( void )
{
float refPoint = dot(u_point, u_normal);
float testPoint = dot(v_worldPosition.xyz, u_normal);
float depth = testPoint - refPoint;
vec3 color = vec3(depth / u_unitLength);
gl_FragColor = vec4( color, 1.0 );
}
You should be aware, that you need to pass fragment position varying v_worldPosition from the vertex shader to fragment shader. I've wrote a simple example for demonstration .
Some optimizations are possible. You can do dot(p, n) not in the shader, but precompute it. For more details read this.
So, it is better to pass the coefficients of plane equation in general form, rather then in point-normal form. The optimized shader would be:
uniform vec4 u_abcd;
uniform float u_unitLength;
varying vec4 v_worldPosition;
void main( void )
{
float depth = dot(u_abcd.xyz, v_worldPosition.xyz) + u_abcd.w;
vec3 color = vec3(depth / u_unitLength);
gl_FragColor = vec4( color, 1.0 );
}
The example of using optimized shader.
You can rotate the plane with your camera, but stay it on the same distance to the object. There is an example. The result is just as you've demonstrated in your gif animation.