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 int
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.