1. 2D坐标的矩阵变换
1.1 对一个点进行平移
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let matrixA = new DOMMatrix("matrix(1,0,0,1,100,200)");
const point = new DOMPoint(10, 20);
const point_r = point.matrixTransform(matrixA);
console.log(point_r.x, point_r.y);//110 220
console.log(matrixA);
console.log(point_r);
// [1 0 100] [10] [1 * 10 + 0 * 20 + 100] [110]
// [0 1 200] · [20] => [0 * 10 + 1 * 20 + 200] => [220]
// [0 0 0 ] [0 ] [0 * 10 + 0 * 20 + 0 ] [0 ]
</script>
</body>
</html>
核心是创建DOMMatrix
、DOMPoint
的两个对象,然后调用DOMPoint
的matrixTransform
方法。
1.2 对一个点先平移,再缩放
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let matrixA = new DOMMatrix("matrix(1,0,0,1,100,200)");
const point = new DOMPoint(10, 20);
const point_r = point.matrixTransform(matrixA);
console.log(point_r.x, point_r.y);//110 220
let matrixB = new DOMMatrix("matrix(10,0,0,10,0,0)");
const point_r2 = point_r.matrixTransform(matrixB);
console.log(point_r2.x, point_r2.y);//1100 2200
</script>
</body>
</html>
1.3 两个变换矩阵先相乘,再乘以点坐标矩阵
矩阵具有结合律,先把所有变换矩阵相乘,成为一个总的变换矩阵,再应用到点坐标。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let matrixA = new DOMMatrix("matrix(1,0,0,1,100,200)");
let matrixB = new DOMMatrix("matrix(10,0,0,10,0,0)");
let matrixBA = matrixB.multiply(matrixA);//计算顺序从左到右:BA
const point = new DOMPoint(10, 20);
const point_r = point.matrixTransform(matrixBA);//
console.log(point_r.x, point_r.y);//1100 2200
</script>
</body>
</html>
核心是调用DOMMatrix
的multiply
方法,进行两个方阵的相乘。