I am working on a HTML5 Canvas demo of spheres bouncing in 3D space. This is very simple to do. Each ball has X, Y, and Z co-ordinates. These co-ordinates are then converted into screen X and Y co-ordinates that I read here. http://answers.google.com/answers/threadview/id/496030.html
The formula that I got from the above link to convert X Y Z co-ordinates into X and Y is
screenX = (depth/(Z+depth)) * X
screenY = (depth/(Z+depth)) * Y
I have put a demonstration of the working code in jsFiddle here. http://jsfiddle.net/xeMpv/
But something is off here. The result I get looks like this. Can you tell me what I am doing wrong?
Currently your origin (origo) is in the top left corner. To project x
and y
so that your origin, or here: the Cartesian coordinate [0, 0, 0]
is in center of the screen:
f = fieldOfView / (viewDistance + z);
px = x * f + screenWidth * 0.5;
py = y * f + screenHeight * 0.5;
fieldOfView
is related to focal distance, use for example 128 - 256.
viewDistance
translates z
values.
px
and py
are the projected 2D coordinates.
If all your coordinates are positive they will be drawn on the right/bottom side of the origin so you need to use negative values to have something on the left/top side of it.
Additionally: you can replace the line operations with rect()
s and if you cache them to an off-screen canvas you can "blit" that to main canvas instead of clearing and re-drawing each time which gives you a little better performance.