用矩阵实现元素绕不定点旋转
用css的transform属性实现元素绕指定点进行旋转。
坐标系原点默认在元素中间,transform的值会对坐标系产生影响。坐标系原点如果不改变transform-origin
就是元素几何中心。
白色的点是坐标系原点。
绿色的点是指定旋转的点。
现在实现效果元素绕绿色点顺时针旋转六十度。
移动坐标系让坐标系原点在指定旋转点的位置,注意旋转中心没有变化还是在元素几何中心。
把坐标系原点挪到旋转点位置。
然后旋转元素,这里旋转的中心点还是在元素几何中心位置。
然后再偏移相同位置回去,注意偏移的移动方向是旋转后的坐标系。
用矩阵可以实现css transform函数的各种效果,都是基于矩阵去做的
本质是将点经过矩阵乘法得出新的点的坐标位置。
矩阵乘法公式
| a b c | | x | | ax + by + c |
| d e f | * | y | = | dx + ey + f |
| 0 0 1 | | 1 | | 1 |
在css坐标系原点其实是元素的几何中心,这是受transform-origin
影响的。
在canvas和svg里,坐标系原点是左上角顶点。
import {fromObject, rotateDEG, translate, compose} from "transformation-matrix"export function rotate(matrix: Matrix, cx: number, cy: number, angle) {const m = fromObject({a: matrix[0],b: matrix[1],c: matrix[2],d: matrix[3],e: matrix[4],f: matrix[5],});// 合并多个矩阵变换的效果,先后顺序不一样导致的结果也不同const rotation = compose(translate(cx, cy), rotateDEG(angle), translate(-cx, -cy)); // 原来矩阵和旋转矩阵合并得到新矩阵const newMatrix = compose(m, rotation);return {matrix: [newMatrix.a, newMatrix.b, newMatrix.c, newMatrix.d, newMatrix.e, newMatrix.f] as Matrix};
}
这里用到了transformation-matrix
提供的矩阵工具函数。
fromObject
: 将对象生成为矩阵对象。
translate
: 平移。
rotateDEG
: 旋转(角度)。
compose
: 将多个变换矩阵合并为一个由多个矩阵组成的矩阵。