css3 Matrix

Matrix

今天终于搞明白的Matrix在css3 transform中是怎么回事了。

在网上查了半天,也都是讲讲怎么用Matrix,也没找到为什么要这样用。

最后找到了opengl的文档,才弄明白。
http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/

2D转换都是33矩阵。3D是44的矩阵。
而实际一个二维空间向量只有两个维度,三维只有三个维度。为什么转换的是否会多了一个,这个问题就让我很困惑。

Until then, we only considered 3D vertices as a (x,y,z) triplet. Let’s introduce w. We will now have (x,y,z,w) vectors.

This will be more clear soon, but for now, just remember this :

If w == 1, then the vector (x,y,z,1) is a position in space.
If w == 0, then the vector (x,y,z,0) is a direction.

可以从上面的描述看出多出的一个维度的作用是指示这个矩阵代表的是一个方向还是一个点。

下面对平面向量 [a b c](c为0或者1,含义同上)

translate(x,y): [1 0 x, 0 1 y, 0 0 1][a b c]=[a+x b+y c]

rotate(deg): [cos(deg) -sin(deg) 0, sin(deg) cos(deg) 0, 0 0 1][a b c]=[acos(deg)-bsin(deg) asin(deg)+bcos(deg) c]

不妨令 a=rcos(w),b=rsin(w), 则上式=[rcos(w+deg) rsin(w+deg) c]

scale(sx,sy): [sx 0 0, 0 sy 0, 0 0 1][a b c]=[sxa syb c]

相信通过上面的几个简单的矩阵变换,可以很明显的看出Matrix在其中的作用。

最后还有一个比较重要的问题,就是合并多个变换的时候,需要注意顺序,并不是完全按照下列公式的顺序。

TransformedVector = TranslationMatrix * RotationMatrix * ScaleMatrix * OriginalVector;

解释如下:

As a matter of fact, the order above is what you will usually need for game characters and other items : Scale it first if needed; then set its direction, then translate it. For instance, given a ship model (rotations have been removed for simplification) :

The wrong way :

  • You translate the ship by (10,0,0). Its center is now at 10 units of the origin.
  • You scale your ship by 2. Every coordinate is multiplied by 2 relative to the origin, which is far away… So you end up with a big ship, but centered at 2*10 = 20. Which you don’t want.

The right way :

  • You scale your ship by 2. You get a big ship, centered on the origin.
  • You translate your ship. It’s still the same size, and at the right distance.

你可能感兴趣的:(css3 Matrix)