Just an addition to WestLangley's answer.
I encountered a small bug that my vertex position was being calculated slightly wrong. Seemed that it was in range of (-1.1, 1.1). So after experimenting it turned out that v.z
is not exactly correct, it is dependent on near field clip plane, which people usually leave as 1 in camera setup. So adding 2 to v.z
seems have fixed it. I don't understand why 2 and not 1.
x = v.x / (v.z + 2.0); // depth + 2 x near clip space plane dist (camera setting)
So if you are working with large objects like in WestLangley's example, you won't notice it, but if your objects are small and close to camera then the error will be noticeable.
I've modified above example to clip color if position is not within (0,1) for Y and fixed calculation for X. Plane size is 20, camera distance is 30.
jsFiddle
It's still not perfect. If object gets very close to the camera it still messes up the position, but at least this makes it work with medium sized objects.