1.0
3.2
3.5
9
10.5
There are two categories of transform - 2D transforms and 3D transforms. 2D transforms are more widely supported, whereas 3D transforms are only in newer browers.
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);
}
CSS transforms also be animated using transitions - try hovering on the div below.
12.0
4.0
10.0
10.0
-
3D CSS transforms are similar to 2D CSS 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: 800px;
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.
Note that because of the way a cube works, the image is moved out towards the screen, and is bigger than it should be. You should move it back by half the width of an image to make sure it is normal size.
Image 1 Image 2 Image 3 Image 4
Click me to toggle transparency
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.
CSS 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.
Comments/Questions?
Please add any questions/corrections/extra info below. Please be courteous to other users.
blog comments powered by Disqus