首页 > 解决方案 > 如何在javascript中计算两个三角形之间的二维变换矩阵

问题描述

我想计算允许将三角形转换为另一个的二维变换矩阵。
两个三角形点的坐标都是已知的。
我通常使用 Paper.js 来处理矩阵,但这个用例不在其中。
我仍然用它来说明我在这个草图中的问题。
请注意,在此示例中,我选择了点坐标和矩阵变换来说明变换的复杂程度,但其想法是能够解决所有可能的情况。 在此处输入图像描述

我认为我在这里找到了理论答案,但我很难用 javascript 对其进行编程,因为我对矩阵数学的了解有限。
有人知道可以解决此类问题的 javascript 库吗?
或者有人知道如何在 javascript 中解决它?

这是我用来说明问题的代码:

// These are the known input points
const p1A = new Point(0, 0);
const p2A = new Point(25, 0);
const p3A = new Point(0, 15);

// This is the matrix that I want to calculate
const matrix = new Matrix();
matrix.translate(40, 0);
matrix.rotate(30);
matrix.scale(1.2, -0.2);
matrix.rotate(-70);

// These are the known transformed points
const p1B = p1A.transform(matrix);
const p2B = p2A.transform(matrix);
const p3B = p3A.transform(matrix);

// Draw the elements to better visualize the problem
drawPoint(p1A, 'p1A', 'red');
drawPoint(p2A, 'p2A', 'cyan');
drawPoint(p3A, 'p3A', 'lime');
drawPoint(p1B, 'p1B', 'red');
drawPoint(p2B, 'p2B', 'cyan');
drawPoint(p3B, 'p3B', 'lime');

drawPolygon([p1A, p2A, p3A], 'A');
drawPolygon([p1B, p2B, p3B], 'B');

// Scale things up to better see.
project.activeLayer.fitBounds(view.bounds.scale(0.8));


//
// METHODS
//

function drawPoint(point, name, color) {
    new Path.Circle({
        center: point,
        radius: 1,
        fillColor: color
    });
    new PointText({
        content: name,
        point: point - [0, 1.5],
        justification: 'center',
        fontSize: 1
    });
}

function drawPolygon(points, name) {
    const path = new Path({
        segments: points,
        strokeColor: 'grey',
        closed: true
    });
    new PointText({
        content: name,
        point: path.bounds.center,
        justification: 'center',
        fontSize: 2
    });
}

标签: javascriptmatrixgeometrypaperjscoordinate-transformation

解决方案


这个问题背后的数学在这篇Wikipedia 文章中有所描述。查看有关增强矩阵的部分,该部分是包含翻译的转换所需的。

在 JavaScript 中,所有必需的操作都可以使用库linalg.js来完成。


推荐阅读