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

I am trying to figure out how to do this. I can not find examples of this and virtually no previous questions. Basically I have 121 thumbnail images (with exactly the same sizes), place them in a grid with gutters, and I want to take the first image and put it in the center. (this allows you to use an 11x11 image grid). Then I would like to take every next image and start arranging them around the central image, using the next closest available free space to the central image until all are used up. It is assumed that the list of images will be obtained from the array object. What is the most efficient way to do this?

+4
source share
1 answer

Most likely, this is not the most effective way to resolve this issue, but I wanted to play with it:

You can iterate over all the points in your grid, calculate their distances to the center point, and then sort the points at that distance. The advantage of algorithmic solutions is that you can use all kinds of remote functions:

// 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; }); 

The resulting pointsWithDistances array will look like this:

 [ {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}, ... ] 

Iterating over the array in this order, you effectively fill the grid from the center out.

Using Euclidean Distances

(Thanks for Andreas Karlbom for the idea of ​​how to display this structure.)

Check the difference using Rectilinear Distance:

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

Using Rectilinear Distances

For the shell structure of algorithmic approaches, you can use the maximum metric:

 // '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)); } 

Using 'Maximum Metric' distances

You can play with the code here: http://jsfiddle.net/green/B3cF8/

+4
source

Source: https://habr.com/ru/post/1392641/


All Articles