There are two distinct responses to your inquiry: a direct solution to your query, and a solution to your dilemma:
In Answer to "How do I calculate the X and Y coordinates of each div?"
Note - The following response is an adaptation of a previous post made for the thread Transform GPS-Points to Screen-Points with Perspective Projection in Android. You can also refer to the Wikipedia article "3D projection" for a broader explanation.
If you wish to perform perspective projection, additional information is required such as the position/orientation of your camera/eye, its field of view angle, and the surface on which you intend to project your cube.
By obtaining this data, you can iterate through your div
elements, then their 4 corner vertices, apply rotation transformation and projection to derive 2D coordinates necessary for rendering the elements.
Implementing Rotation
We'll simplify by considering:
- A vertex A(x_0, y_0, z_0), one of the corners of your
div
- θ and δ representing the angles for desired rotation, specifically the pitch angle and yaw angle (Tayt-Brian angles)
We aim to determine:
- D(x,y,z), the position of our rotated element
The linearized equations become:
x = sin(δ) * y_0 + cos(δ) * x_0
y = sin(θ) * z_0 + cos(θ) * (cos(δ) * y_0 − sin(δ) * x_0)
z = cos(θ) * z_0 i sin(θ) * (cos(δ) * y_0 − sin(δ) * x_0)
Projection Overview
Given:
- Our point D(x,y,z)
- w * h, the dimension of the target surface (
innerWidth
* innerHeight
in this context)
- A half-angle of view α
Our objective:
- The coordinates of B on the surface plane (referred to as X and Y)
Note: Similar approach for determining Y.
Application
Key points include:
- Typically, α = 45deg is utilized, eliminating the need for
tan(α)
in many scenarios.
- To preserve aspect ratio, maintain f constant for both X and Y, rather than conducting separate calculations for each.
- Adjust screen coordinates to align with expected display area ranges.
Tackling the Challenge of Rendering a 3D Cube using div
The previously outlined method may encounter limitations when implementing the projected div
elements due to potential distortion affecting their appearance and complicating CSS-based rendering.
For showcasing a 3D DOM cube with rotations and depth perception, consider leveraging CSS3 3D transforms to offload computational tasks to the browser.
Benefits include:
- Utilization of GPU acceleration for smoother performance compared to JS implementations.
- Automatic handling of content modifications based on transformations applied.
- No requirement for extensive mathematical computations.
For dynamic cube rotation, utilize JS to manipulate CSS transforms accordingly.
Illustrative Example
An interactive demo on JSFiddle showcases implementation inspired by the tutorial with added functionality for rotational updates triggered by mouse movements.
Trust this proves beneficial! Goodbye!