Rotation matrix - https://jsfiddle.net/pq62hx0t/4/
function matrixArrayToCssMatrix(array) { | |
return "matrix3d(" + array.join(',') + ")"; | |
} | |
function multiplyMatrixAndPoint(matrix, point) { | |
//Give a simple variable name to each part of the matrix, a column and row number | |
var c0r0 = matrix[0], | |
c1r0 = matrix[1], | |
c2r0 = matrix[2], | |
c3r0 = matrix[3]; | |
var c0r1 = matrix[4], | |
c1r1 = matrix[5], | |
c2r1 = matrix[6], | |
c3r1 = matrix[7]; | |
var c0r2 = matrix[8], | |
c1r2 = matrix[9], | |
c2r2 = matrix[10], | |
c3r2 = matrix[11]; | |
var c0r3 = matrix[12], | |
c1r3 = matrix[13], | |
c2r3 = matrix[14], | |
c3r3 = matrix[15]; | |
//Now set some simple names for the point | |
var x = point[0]; | |
var y = point[1]; | |
var z = point[2]; | |
var w = point[3]; | |
//Multiply the point against each part of the 1st column, then add together | |
var resultX = (x * c0r0) + (y * c0r1) + (z * c0r2) + (w * c0r3); | |
//Multiply the point against each part of the 2nd column, then add together | |
var resultY = (x * c1r0) + (y * c1r1) + (z * c1r2) + (w * c1r3); | |
//Multiply the point against each part of the 3rd column, then add together | |
var resultZ = (x * c2r0) + (y * c2r1) + (z * c2r2) + (w * c2r3); | |
//Multiply the point against each part of the 4th column, then add together | |
var resultW = (x * c3r0) + (y * c3r1) + (z * c3r2) + (w * c3r3); | |
return [resultX, resultY, resultZ, resultW]; | |
} | |
// 將 float 轉成 number 避免出現 -1.23-e 這種值 | |
const to = n => Number(n.toFixed(2)) | |
var sin = Math.sin; | |
var cos = Math.cos; | |
// cx/y = current x, y 以左上角為準 | |
function rotate(rotation, w, h, cx, cy) { | |
// degree to radian | |
var a = rotation * (Math.PI / 180) | |
// | |
var rotateZMatrix = [ | |
cos(a), -sin(a), 0, 0, | |
sin(a), cos(a), 0, 0, | |
0, 0, 1, 0, | |
0, 0, 0, 1 | |
]; | |
// 不管中心點位置,一律反推出左上角座標 | |
const diffX = w / 2 | |
const diffY = h / 2 | |
const x = -diffX | |
const y = -diffY | |
// 方型左上角距 (0, 0) 的距離,通常直接讀取方型的 (x, y) 就夠 | |
const offsetX = cx | |
const offsetY = cy | |
// 然後與 rotation matrix 相乘得到旋轉後位置 | |
const [x1, y1] = multiplyMatrixAndPoint(rotateZMatrix, [x, y, 0, 1]) | |
// 原點不在 (0,0) 時要加上離原點的位移值 | |
const finalX = to(x1 + diffX + offsetX) | |
const finalY = to(y1 + diffY + offsetY) | |
console.log('\n\n', { finalX, finalY }, '\t', { x, y, diffX, diffY, w, h }) | |
} | |
// 測試 | |
console.log(rotate(45, 100, 100, 0, 0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment