Just the weekly tutorials.

CSS 3D Transformations Rotating Coke

I have spent some time experimenting with 3D CSS transforms in Chrome. I believe this demo requires a computer capable of hardware accelerated graphics. If not, then the cylinder textured as a coke can may appear flat. Transformations are done using the transform property in CSS.

This demo was written exclusively for Chrome and shows how transforms are not yet supported on just any operating system or in any browser. Another reason to consider HTML5's canvas tag for future graphics demos.

If this looks flat (like someone with a perfectly flat shoe stepped on the coke) then your browser or operating system does not support hardware accelerated graphics.

Here is the HTML. Notice a <UL> tag for each side of the coke. The JavaScript program creates a 3D cylinder automatically from the number of the sides represented by <LI> tags.

<section id = "v"> <section id = "p-3d"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </section> </section>

To figure out how far each side is from the center I used the classic sin/cos formula which takes a 0-360 angle and returns the direction as a 2D vector:

function DIR(angle) { var dirx = Math.sin(parseFloat(angle) * Math.PI / 180.0); var diry = -Math.cos(parseFloat(angle) * Math.PI / 180.0); return [dirx, diry]; }

The returned values dirx and diry contain the vector direction. They can be applied on any axis pair in 3D space and are not limited to [X, Y] pair. The resulting array returned from this function can be used depending on the purpose of the logic in your 3D program. In this case, the values will be applied to axis Y and Z because X is the axis around which the cylinder is formed.

Real-time Animation

The animation is achieved using the JavaScript timer function setInterval. CSS transform is applied using jQuery's .css() method. This is a -webkit only example. The actual property is transform and for other browsers: -moz-transform, -ms-transform, etc.

function start_loop(){ $("#p-3d").css({ '-webkit-transform': 'rotateY('+ANG+'deg) ' + 'rotateX('+ANG+'deg) ' + 'rotateZ('+ANG+'deg)' }); ANG++; // increase angle } // Begin animation var t = setInterval(start_loop, 30); // call every 30 milliseconds

Here the code arbitrarily applies the same rotation angle to all axis. This achieves the rotation effect seen in the demo.

Just the weekly tutorials.