Generate random element position and prevent overlapping in JavaScript

冷暖自知 提交于 2019-11-29 04:53:53

Store the picked coordinates in an array, so that you can compare the coordinates of each new image you place against the previous.

If the coordinates that you picked overlaps a previous image, pick new coordinates. Limit the number of tries so that if you can't place an image with say 1000 tries, you start over with the first image.

Sorry for digging out an old post, but I recently came across a similar problem and it took me some time to find the perfect solution - that I now wanted to share. There are tree ways to achieve this.


1) The hard way

If you'd like to implement it on your own, you will probably achieve the result best fitting your needs. It does require some time and lots of testing but actually it's not that difficult to implement such a feature on your own. You can use the Random-Functions Math.floor(Math.random() * Max) + Min to calculate a random position in the parent element. After positioning the first element, you need to store the coordinates of the element, in an array for instance. Now before you show the next element you can use the array to check if there are overlaps - if so, you can just calculate a new position. Isn't the most efficient way to do this probably but it'll work quite well for not so big amounts of elements. But I'm pretty sure that if you implemented this, it's also not too difficult to optimize your algorithm in order to make this more efficient.

2) The workaround way

The second way to achieve this is ways easier then the first way but also not as flexible. Therefore you'd need to use some predefined layout - some kind of a grid. So lets assume that you have a container with 100 grid-blocks, so 100 elements to put your elements in. You could now just calculate a random number between 1 and 100 and append your element to the grid-container. It's quite easy to prevent overlapping but this way of doing it might not always fit your needs.

3) The easiest way If searched quite a while but there was not a single plugin which fit my needs. So I created one on my own, which I published and which can be used for free. You can find it under manuelmaurer.at/randposplugin.php. It's pretty flexible so I think this one would be the easiest way for you to achieve your goals.

I guess there is no plugin. I will implement this like Sander suggested by making predefined div grid and just loading random images to those divs. It's easier and faster than calculating image dimenssions/positions and does pretty much the same job. Not random but visually looks good :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!