一、矩阵
首先了解矩阵的计算规则
|a c e| |x| |ax + cy + 2e|
|b d f| * |y| = |bx + dy + 2f|
|1 1 2| |2| |x + y + 4 |
|a c e| |x j| |ax + cy + 2e aj + ck + e|
|b d f| * |y k| = |bx + dy + 2f bj + dk + f|
|1 1 2| |2 1| |x + y + 4 j + k + 2|
矩阵相乘,需要前一个矩阵的列数等于后一个矩阵的行数
二、matrix
1.translate(x,y)
同样是利用矩阵,其中translateX,translateY为translate(x,y)中的x,y的值,那么我们怎样计算出最前面的a,b,c,d,e,f的值?
|a c e| | x | | x + translateX|
|b d f| * | y | = | y + translateY|
|0 0 1| | 1 | | 1 |
//|0 0 1|该行只是用来填充矩阵的,实际只用到上两层
通过前面提到的矩阵知识,我们很容易得出:
1 * x+0 * y+translateX * 1=x + translateX
0 * x+1 * y+translateY * 1=y + translateY
所以我们得出矩阵为
|1 0 translateX|
|0 1 translateY|
|0 0 1 |
那么根据上下上下填入matrix得出
matrix(1,0,0,1,translateX,translateY) === translate(translateX,translateY)
2.scale(n,m)
同上,利用矩阵,其中n,m为scale(n,m)中的n,m的值,那么我们怎样计算出最前面的a,b,c,d,e,f的值?
|a c e| | x | | nx|
|b d f| * | y | = | my|
|0 0 1| | 1 | | 1 |
//|0 0 1|该行只是用来填充矩阵的,实际只用到上两层
n * x+0 * y+0 * 1=nx
0 * x+m * y+0 * 1=my
所以我们得出矩阵为
|n 0 0|
|0 m 0|
|0 0 1|
那么根据上下上下填入matrix得出
matrix(n,0,0,m,0,0) === scale(n,m)
3.rotate(θ)
其中需要计算cos(θ)和sin(θ)比较复杂,所以一般都是只用rotate(θ)
这里只是简单介绍
|cos(θ) -sin(θ) e| | x |
|sin(θ) cos(θ) f| * | y | = rotate(θ)
| 0 0 1| | 1 |
//|0 0 1|该行只是用来填充矩阵的,实际只用到上两层
最终:
matrix(cos(θ),sin(θ),-sin(θ),cos(θ),0,0) === rotate(θ)
三、实现功能
1.左右倒置
如果一张图片的左右倒置怎么实现?
从目的我们直接分析结果:
| -x |
| y |
| 1 |
那么很容易计算出
|-1 0 0|
| 0 1 0| = matrix(-1,0,0,1,0,0)
| 0 0 1|
如果在matrix(-2,0,0,1,0,0)呢?将会倒置再拉伸