canvas/pages/index/transform-matrix.js
2025-08-12 18:01:11 +08:00

77 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class TransformMatrix {
constructor() {
this.reset();
}
reset() {
this.a = 1; // 水平缩放
this.b = 0; // 垂直倾斜
this.c = 0; // 水平倾斜
this.d = 1; // 垂直缩放
this.tx = 0; // 水平移动
this.ty = 0; // 垂直移动
this.stack = [];
}
translate(dx, dy) {
this.tx += this.a * dx + this.c * dy;
this.ty += this.b * dx + this.d * dy;
}
scale(sx, sy, cx = 0, cy = 0) {
// 移动到中心点
this.translate(cx, cy);
// 应用缩放
this.a *= sx;
this.b *= sx;
this.c *= sy;
this.d *= sy;
// 移回原位置
this.translate(-cx, -cy);
}
toArray() {
return [this.a, this.b, this.c, this.d, this.tx, this.ty];
}
// 用于调试的字符串表示
toString() {
return `[${this.a.toFixed(2)}, ${this.b.toFixed(2)}, ${this.c.toFixed(2)}, ${this.d.toFixed(2)}, ${this.tx.toFixed(1)}, ${this.ty.toFixed(1)}]`;
}
// 克隆方法
clone() {
const clone = new TransformMatrix();
clone.a = this.a;
clone.b = this.b;
clone.c = this.c;
clone.d = this.d;
clone.tx = this.tx;
clone.ty = this.ty;
return clone;
}
// 添加点坐标转换方法
transformPoint(x, y) {
return {
x: this.a * x + this.c * y + this.tx,
y: this.b * x + this.d * y + this.ty
};
}
// 添加逆矩阵转换方法
invertPoint(x, y, dpr) {
console.log('invertPoint',dpr)
const det = this.a * this.d - this.b * this.c;
if (Math.abs(det) < 0.0001) return {x, y};
return {
x: (this.d * (x/dpr - this.tx) - this.c * (y/dpr - this.ty)) / det,
y: (this.a * (y/dpr - this.ty) - this.b * (x/dpr - this.tx)) / det
};
}
}
export default TransformMatrix;