There are two categories of transform - 2D transforms and 3D transforms. As of May 2010, 3D transforms only work in Safari (both desktop and mobile). 2D transforms are more widely supported.
The code for these looks like this, but with the appropriate vendor prefixes added:
#skew {
transform:skew(35deg);
}
#scale {
transform:scale(1,0.5);
}
#rotate {
transform:rotate(45deg);
}
#translate {
transform:translate(10px, 20px);
}
#rotate-skew-scale-translate {
transform:skew(30deg) scale(1.1,1.1) rotate(40deg) translate(10px, 20px);
}
These can also be animated using transitions - try hovering on the div below.
3D transforms work in Safari, Chrome, Firefox 10+ and IE10
3D transforms are similar to 2D transforms. The basic properties are translate3d, scale3d, rotateX, rotateY and rotateZ. Translate3d and scale3d take three arguments for x,y and z, whereas the rotates just take an angle. Here are some examples:
Hover me
The simplified code for those looks like this:
#transDemo4 div {
transition:all 2s ease-in-out;
perspective: 800;
perspective-origin: 50% 100px;
}
#transDemo4:hover #rotateX {
transform:rotateX(180deg);
}
#transDemo4:hover #rotateY {
transform:rotateY(180deg);
}
#transDemo4:hover #rotateZ {
transform:rotateZ(180deg);
}
1
2
3
4
5
6
Have a play with the controls - there's no transition here, just the sliders to control it. Note that I'm only using javascript to update the css values - all the maths needed is done by the browser automatically.
Original
Transformed
For more information read both the Webkit blog entry from when 3D transforms were first implemented, David Desandro's awesome examples and Microsoft's 3D transforms test drive.
Though it's rare that you'll need it, it's worth noting that the raw matrix implementations are exposed as well. As an example, the skew transform above has a skew of 35 degrees. To find the internal representation, you can use javascript to find the computed style. In this case, skew(35deg) is represented by matrix(1, 0, 0.7002075382097097, 1, 0, 0). The astute among you will note that this is a 2×3 matrix. To use them for normal arithmetic, add a third row of 0, 0, 1.
3D transforms are represented similarly, with a 4×4 matrix.
Understanding how to create these matrices is probably out of the scope of this tutorial, but an undergraduate understanding of matrix algebra should suffice. Read the Wikipedia article on transformation matrices for a quick primer.
For the exact methods, read the part of the spec about 2D matrix decomposition and 3D matrix interface.
Please add any questions/corrections/extra info below. Please be courteous to other users.
blog comments powered by Disqus