transformation-matrix
Version:
2d transformation matrix functions written in ES6 syntax. Tree shaking ready!
45 lines (41 loc) • 1.22 kB
JavaScript
import { isUndefined } from './utils'
import { translate } from './translate'
import { transform } from './transform'
const { cos, sin, PI } = Math
/**
* Calculate a rotation matrix
* @param angle {number} Angle in radians
* @param [cx] {number} If (cx,cy) are supplied the rotate is about this point
* @param [cy] {number} If (cx,cy) are supplied the rotate is about this point
* @returns {Matrix} Affine Matrix
*/
export function rotate (angle, cx, cy) {
const cosAngle = cos(angle)
const sinAngle = sin(angle)
const rotationMatrix = {
a: cosAngle,
c: -sinAngle,
e: 0,
b: sinAngle,
d: cosAngle,
f: 0
}
if (isUndefined(cx) || isUndefined(cy)) {
return rotationMatrix
}
return transform([
translate(cx, cy),
rotationMatrix,
translate(-cx, -cy)
])
}
/**
* Calculate a rotation matrix with a DEG angle
* @param angle {number} Angle in degree
* @param [cx] {number} If (cx,cy) are supplied the rotate is about this point
* @param [cy] {number} If (cx,cy) are supplied the rotate is about this point
* @returns {Matrix} Affine Matrix
*/
export function rotateDEG (angle, cx = undefined, cy = undefined) {
return rotate(angle * PI / 180, cx, cy)
}