ythy / blog

Give everything a shot
7 stars 0 forks source link

Discover: Rotations with matrices #314

Open ythy opened 4 years ago

ythy commented 4 years ago

二角和差公式

sin(a + b)=sinacosb + sinbcosa
sin(a - b)=sinacosb - sinbcosa
cos(a + b)=cosacosb - sinasinb
cos(a - b)=cosacosb + sinasinb

证明公式: 证明

旋转公式证明

推导过程如下:

  1. 假定当前坐标点为 ( x, y ) , 与原点在水平轴夹角为t, 那么 ( x, y ) 也可表示为 ( cos t, sin t ) image

  2. 假定该点以原点(0, 0)为中心旋转θ度, 由于半径不变,那么旋转后的点可以表示为 ( cos t + θ, sin t + θ )

  3. 根据角度和公式,上述坐标可表示为( cos t * cos θ - sin t * sin θ, sin t * cos θ + sin θ * cos t )

  4. 上述坐标简化为( x * cos θ - y * sin θ, x * sin θ + y * cos θ ), 矩阵得出

代码实战

https://github.com/ythy/blog/blob/master/files/test_svg_animate.html

手写Matrix乘法

https://github.com/ythy/blog/blob/master/files/test_matrix_multiplication.html

ythy commented 4 years ago

transform link

ythy commented 4 years ago

If you rotate point (px, py) around point (ox, oy) by angle theta you'll get:

p'x = cos(theta) * (px-ox) - sin(theta) * (py-oy) + ox
p'y = sin(theta) * (px-ox) + cos(theta) * (py-oy) + oy

this is an easy way to rotate a point in 2D.

ythy commented 4 years ago

Matrix It is possible to express transformations as a matrix too. The matrix looks like this:

a  c  e
b  d  f
0  0  1

Since only the first 6 values can be specified, you only provide 6 values to the matrix transformation function. Here is an example:

transform="matrix(a,b,c,d,e,f)"

The other transformation functions can be expressed as matrices. Here are some examples:

Translate

1  0  tx
0  1  ty
0  0   1

matrix(1,0,0,1,tx,ty)
Rotate

cos(a)   -sin(a)  0
sin(a)    cos(a)  0
     0        0   1

matrix( cos(a), sin(a),-sin(a),cos(a),0,0 )

Note: the values for cos(a) and sin(a) have to be precomputed before being inserted into the matrix. The parameter a is the angle to rotate.

Scale

sx  0  0
 0 sy  0
 0  0  1

matrix(sx,0,0,sy,0,0)

A skew transformation along the x-axis can be written as:

Skew

1  tan(a)  0
0       1  0
0       0  1

matrix(1,0,tan(a),1,0,0)

The tan(a) value has to be precomputed before being inserted into the matrix() function.

A skew transformation along the y-axis can be written as:

Skew

1       0  0
tan(a)  1  0
0       0  1

matrix(1,tan(a),0,1,0,0)