Randomly placing images within a <div> and ensuring uniform distribution
I have a rectangular html div with dimensions X by Y. Lets say the center of this div is at x(c) and y(c). I have N images of dimension x(i) and y(i). The images sizes are roughly around 1/8th of the containing div and each image size is different from the rest.
What could be a good way to place these images inside this div so that they are uniformly distributed (yet randomly placed) on each page load. Looking a开发者_运维百科t a javascript implementation.
EDIT: After dascandys answer, I think I could have worded the question better. I meant a random sequence of image load on each page load yet keeping the look and feel balanced.
You're not actually looking for a random distribution. Truly random means that parts of it are empty and that in another corner two of them overlap.
If you want to go scientific, you can use a randomly generated Voronoi diagram with N points and Lloyd's algorithm to move those to a more uniform distribution.
If you prefer the practical approach, just put them in random spots and iteratively see if they're overlapping and if so, move them apart. For 8 images this'll be slower but still beyond human perception quick.
This is what spatial Poisson distribution was invented for. Try e.g. this link to see how to generate the points. I would go for some Monte Carlo method for generating random points in 2D (use google).
There is also one very simple method called jittering, but it is not so elaborated as Poisson and MC. You just define a rectangular maze of points and then just "jitter" the points randomly:
for i = 1 .. m
for j = 1 .. n
ouput point [i * maze_size + rand(maze_size/2),
j * maze_size + rand(maze_size/2)]
精彩评论