簡體   English   中英

使用javascript徑向排列圖像的最有效方法是什么?

[英]What is the most efficient way to arrange images radially using javascript?

我一直在努力研究如何使這項工作。 我找不到這個例子,實際上沒有先前的問題。 基本上我有121個縮略圖(具有完全相同的尺寸),將它們排列在帶有水槽的網格中,我想拍攝第一張圖像並將其放在中心。 (這允許11x11圖像網格)然后我想拍攝每個下一個圖像並開始圍繞中心圖像使用下一個最近可用的空位置到中心圖像​​排列它們直到所有用完。 假設圖像列表將從數組對象中獲取。 這樣做最有效的方法是什么?

很可能不是最有效的解決方法,但我想玩它:

您可以迭代網格中的所有點,計算它們到中心點的距離,然后按此距離對點進行排序。 算法解決方案的優勢在於您可以使用各種距離函數:

// Setup constants
var arraySize = 11;
var centerPoint = {x:5, y:5};

// Calculate the Euclidean Distance between two points
function distance(point1, point2) {
    return Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2));
}

// Create array containing points with distance values
var pointsWithDistances = [];
for (var i=0; i<arraySize; i++) {
    for (var j=0; j<arraySize; j++) {
        var point = {x:i, y:j};
        point.distance = distance(centerPoint, point);
        pointsWithDistances.push(point);
    }
}

// Sort points by distance value
pointsWithDistances.sort(function(point1, point2) {
    return point1.distance == point2.distance ? 0 : point1.distance < point2.distance ? -1 : 1;
});

生成的pointsWithDistances數組將如下所示:

[
    {x:5, y:5, distance:0},
    {x:4, y:5, distance:1},
    {x:5, y:4, distance:1},
    ...
    {x:4, y:4, distance:1.4142135623730951},
    {x:4, y:6, distance:1.4142135623730951},
    ...
    {x:3, y:5, distance:2},
    ...
]

通過按此順序迭代數組,您可以有效地從中心向外填充網格。

使用歐幾里德距離

(感謝Andreas Carlbom關於如何顯示這種結構的想法。)

查看使用直線距離的差異:

// Rectilinear Distance between two points
function distance(point1, point2) {
    return Math.abs(point1.x - point2.x) + Math.abs(point1.y - point2.y);
}

使用直線距離

對於算法方法的類似shell的結構,您可以使用最大度量標准:

// 'Maximum Metric' Distance between two points
function distance(point1, point2) {
    return Math.max(Math.abs(point1.x - point2.x), Math.abs(point1.y - point2.y));
}

使用“最大公制”距離

你可以在這里玩代碼: http//jsfiddle.net/green/B3cF8/

暫無
暫無

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

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