How to position a single image by adding to a div at random positions, but within a certain width and height using javascript?

I want the position to add an image inside a div. The image should be displayed 5 times at a height of 500 and a width of 500. They should be randomly located in different places, but they should not intersect the height and width of the div. But my code gives a result where the images are always located in an oblique line from right to left and always create faces that are together.

Here is my code:

        var theLeftSide = document.getElementById("leftSide");  
        var top_position = Math.random() *   500 - 100;
        var left_position = Math.random() *  500 - 100;
        numberOfFaces = 5;
        function generateFaces() {          
            for (var i = 0; i < 6; i++) {
                createElement(i);
                numberOfFaces += numberOfFaces;
            }
        } 
        function createElement() {
            var image = document.createElement('img');
            image.src = "smile.png";
            image.style.position = 'absolute';
            image.style.top = top_position + "px";
            image.style.left = left_position + "px";
            theLeftSide.appendChild(image);
            top_position += 20;
            left_position += 20;
        }
+4
source share
1 answer

, top_position left_position 20 . , . 10, 15, . 30, 45, 50, 65 .. , .

, . getRandomInt MDN (), .

var theLeftSide = document.getElementById("leftSide");  
var top_position;
var left_position;
numberOfFaces = 5;
function generateFaces() {        
    for (var i = 0; i < 6; i++) {
        top_position = getRandomInt(0, 500);
        left_position = getRandomInt(0, 500);
        createElement(i);
        numberOfFaces += numberOfFaces;
    }
} 
function createElement() {
    var image = document.createElement('img');
    image.src = "smile.png";
    image.style.position = 'absolute';
    image.style.top = top_position + "px";
    image.style.left = left_position + "px";
    theLeftSide.appendChild(image);
}
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

, div. div position relative, , divs (, ). , , , .

+2

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


All Articles