Generate random element position and prevent overlapping in JavaScript

前端 未结 3 1011
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 08:13

I have a holder div on the page where I want to load small images in on random position as a collage with 10px padding on each.

How can I make sure that images neve

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-18 08:39

    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.

提交回复
热议问题