簡體   English   中英

jQuery:排序4點到(左上,右上,右下,左下)

[英]jquery: sort 4 points to (top-left, top-right, bottom-right, bottom-left)

給定:2個數組,每個數組包含4個點的坐標:

point_array_a = [point_a_1_x, point_a_1_y, point_a_2_x, ..., point_a_4_y]
point_array_b = [point_b_1_x, ...                       ..., point_b_4_y]

任務:

  1. 對point_array_a進行排序,以便最后按以下順序列出點:

     point_array_a_sorted = [top-left_x, top_left_y, top-right_x, top-right_y, bottom-right_x, bottom_right_y, bottom-left_x, bottom_left_y] 
  2. 以相同的方式對point_array_b進行排序,以使point_a_k_l對應於開始時的point_b_k_l。

恐怕沒有簡單的算法可以做到這一點。 但是下面的代碼片段就可以了(假設y坐標較大的點低於y坐標較低的點):

var i, points = [], leftX = point_array_a[0], topY = point_array_a[1];

for (i = 0; i < 4; i++)
{
    leftX = Math.min(leftX, point_array_a[i * 2]);
    topY = Math.min(topY, point_array_b[i * 2]);
    points.push([
                 [point_array_a[i * 2], point_array_a[i * 2 + 1]],
                 [point_array_b[i * 2], point_array_b[i * 2 + 1]]
                ]);
}

points.sort(function(first, second){
    if (first[0][0] == leftX)
        return first[0][1] == topY ? -1 : 1;
    if (second[0][0] == leftX)
        return second[0][1] == topY ? 1 : -1;
    return first[0][1] < second[0][1] ? -1 : 1;
});

var point_array_a_sorted = [], point_array_b_sorted = [];

for (i = 0; i < 4; i++)
{
    point_array_a_sorted.push(points[i][0][0], points[i][0][1]);
    point_array_b_sorted.push(points[i][1][0], points[i][1][1]);
}

我們通過為現有的Array.sort函數提供正確的對象來進行比較和交換(成對的點)來利用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM