# 寫個 2D 矩陣庫

``````[
1, 0, tx,
0, 1, ty,
0, 0, 1
]
``````

``````[
row1
row2
row3
]
``````

``````[
1,   0,  0,
0,   1,  0,
tx, ty,  1
]
``````

``````[column1 column2 column3]
``````

``````applyMatrix(
a, b,
c, d,
e, f
);
``````

``````const mat3 = {
// 移動矩陣
translation(tx, ty) {
return [
1,  0, 0,
0,  1, 0,
tx, ty, 1
];
},

// 縮放矩陣
scaling(sx, sy) {
return [
sx,  0,  0,
0, sy,  0,
0,  0,  1
];
},

// 旋轉矩陣
rotation(degree) {
const c = cos(degree);
const s = sin(degree);
return [
c, s, 0,
-s, c, 0,
0, 0, 1,
];
},

// 反射矩陣（以 (x, y) 向量為鏡）
reflection(x, y) {
const uu = pow(createVector(x, y).mag(), 2);

const xx = x * x;
const yy = y * y;
const xy2 = x * y * 2;

return [
(xx - yy) / uu, xy2 / uu, 0,
xy2 / uu, (yy - xx) / uu, 0,
0, 0, 1,
];
},

// 移動
translate(m, tx, ty) {
return this.multiply(m, this.translation(tx, ty));
},

// 縮放
scale(m, sx, sy) {
return this.multiply(m, this.scaling(sx, sy));
},

// 旋轉
rotate(m, degree) {
return this.multiply(m, this.rotation(degree));
},

// 反射（以 (x, y) 向量為鏡）
reflect(m, x, y) {
return this.multiply(m, this.reflection(x, y));
},

// 轉為 applyMatrix 可用參數
forApplyMatrix(m) {
return m.filter((elem, idx) => (idx + 1) % 3 !== 0);
},

// 矩陣相乘
multiply(a, b) {
const a00 = a[0], a01 = a[1], a02 = a[2];
const a10 = a[3], a11 = a[4], a12 = a[5];
const a20 = a[6], a21 = a[7], a22 = a[8];

const b00 = b[0], b01 = b[1], b02 = b[2];
const b10 = b[3], b11 = b[4], b12 = b[5];
const b20 = b[6], b21 = b[7], b22 = b[8];

return [
b00 * a00 + b01 * a10 + b02 * a20,
b00 * a01 + b01 * a11 + b02 * a21,
b00 * a02 + b01 * a12 + b02 * a22,

b10 * a00 + b11 * a10 + b12 * a20,
b10 * a01 + b11 * a11 + b12 * a21,
b10 * a02 + b11 * a12 + b12 * a22,

b20 * a00 + b21 * a10 + b22 * a20,
b20 * a01 + b21 * a11 + b22 * a21,
b20 * a02 + b21 * a12 + b22 * a22
];
}
};
``````