我一直在思考如何使其工作。我找不到相关的例子,也没有以前的问题。基本上,我有121个缩略图图像(具有完全相同的尺寸),将它们排列成带间距的网格,并想将第一张图片放在中心位置。 (这允许11x11的图像网格) 然后,我想采取每个下一个图像并开始安排它们围绕中心图像使用最接近中心图像的可用空位,直到用完为止。假设图像列表将从数组对象获取。完成此操作最高效的方法是什么?
我一直在思考如何使其工作。我找不到相关的例子,也没有以前的问题。基本上,我有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);
}
对于算法方法的壳结构,您可以使用最大度量:
// '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/