nodebook/Miscellaneous/transformMatrix.md
2019-10-23 18:04:56 +08:00

135 lines
3.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# CSS的transforn详解
## 使用正常的方法
```css
.demo{
transform:translate(10px, 20px) rotate(30deg) scale(1.5, 2);
}
```
## matrix
```css
.demo{
transform:matrix(0.75, 0.8, -0.8, 1.2, 10, 20)
}
```
## matrix 与矩阵对应
```css
.demo{
transform:matrix(a,b,c,d,e,f)
}
```
![矩阵](https://upload-images.jianshu.io/upload_images/10991556-81fa02fdd6ce61ff.png?imageMogr2/auto-orient/strip|imageView2/2/w/997)
* 2D的转换是由一个3*3的矩阵表示的前两行代表转换的值分别是 a b c d e f 要注意是竖着排的第一行代表的是X轴变化第二行代表的是Y轴的变化第三行代表的是Z轴的变化2D不涉及到Z轴这里使用 0 0 1
## 缩放scale(x,y)
* 缩放对应的是矩阵中的a和dx轴的缩放比例对应a,y轴的缩放比例对应d。
```css
transform:scale(x,y)
a = x
d = y
```
* 所以scale(1.5, 2)对应的矩阵是
* `matrix:(1.5,0,0,0,2,0)`
![缩放矩阵](https://upload-images.jianshu.io/upload_images/10991556-8ee2ef06470e98a1.png?imageMogr2/auto-orient/strip|imageView2/2/w/1080)
* 默认的话a=d=1 记住缩放是对角线
## 平移 translate(10, 20)
* 平移对应的是矩阵中 e 和 f平移的x 和 f分别对应 e 和 f
```css
transform:translate(10, 20)
e = 10
f = 20
```
* 对应:`transform: matrix(a, b, c, d ,10, 20);`
* 结合缩放:`transform: matrix(1.5 0, 0, 2, 10, 20)`
* 这里的ef就是矩阵的最右边的值
## 旋转 rotate(0deg)
* 旋转影响的是a/b/c/d四个值分别是什么呢
```css
transform: rotate(θdeg)
a=cosθ
b=sinθ
c=-sinθ
d=cosθ
```
* 如果要计算 30° 的sin值
* 首先我们要将 30° 转换为弧度,传递给三角函数计算。用 JS 计算就是下面的样子了。
```js
// 弧度和角度的转换公式:弧度=π/180×角度
const radian = Math.PI / 180 * 30 // 算出弧度
const sin = Math.sin(radian) // 计算 sinθ
const cos = Math.cos(radian) // 计算 cosθ
console.log(sin, cos) // 输出 ≈ 0.5, 0.866
```
```css
transform: rotate(30deg)
a=0.866
b=0.5
c=-0.5
d=0.866
transform: matrix(0.866, 0.5, -0.5, 0.866, 0, 0);
```
## 偏移 skew(20deg, 30deg)
* 上面的题目中没有出现出现偏移值偏移值也是由两个参数组成x 轴和 y 轴,分别对应矩阵中的 c 和 b。是 x 对应 cy 对应 b 这个对应并不是相等,需要对 skew 的 x 值 和 y 值进行 tan 运算。
```css
transform: skew(20deg, 30deg);
b=tan30°
c=tan20°
注意 y 对应的是 cx 对应的是 b。
transform: matrix(a, tan(30deg), tan(20deg), d, e, f)
```
* 使用 JS 来算出 tan20 和 tan30
```js
// 先创建一个方法直接返回角度的tan值
function tan (deg) {
const radian = Math.PI / 180 * deg
return Math.tan(radian)
}
const b = tan(30)
const c = tan(20)
console.log(b, c) // 输出 ≈ 0.577, 0.364
b=0.577 c=0.364
transform: matrix(1, 0.577, 0.364, 1, 0, 0)
```
## 旋转+缩放+偏移+位移
* 如果我们既要旋转又要缩放又要偏移我们需要将旋转和缩放和偏移和位移多个矩阵相乘要按照transform里面rotate/scale/skew/translate所写的顺序相乘。
这里我们先考虑旋转和缩放,需要将旋转的矩阵和缩放的矩阵相乘