본문 바로가기
Front-end/JavaScript

JavaScript 랜덤한 위치에 dom요소 생성

DOM요소를 랜덤한 위치에 생성하는 방법을 알아보자.

우선 js 로 html을 조작하기 위해서는 해당 html을 특정하는 변수가 필요하다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>create_dom</title>
    <script src="/main.js" defer></script>
  </head>
  <body>
    <section class="field">
    </section>
  </body>
</html>

위 section 내부 랜덤한 위치에 div를 생성한다고 가정하여 보자.

const field = document.querySelector('.field');

우선 첫번째로 field를 골라 변수에 담아둔다.

 

const fieldRect = field.getBoundingClientRect();

임의의 돔요소의 rect를 출력한 값

dom요소의 전반적 위치와 크기 등의 필요한 정보는 getBoundingClientRect() 를 이용하면 구 할 수 있다.

 

    const newDiv = document.createElement('div');
    newDiv.style.width = `${30}px`; 
    newDiv.style.height = `${30}px`;
    newDiv.style.backgroundColor = 'blue';
    field.appendChild(newDiv);

해당 코드로 새로운 div를 만들고 field에 appendChild를 이용하면 손쉽게 field내부에 생성이 가능하다.

이제 그렇다면 랜덤한 위치에 어떻게 생성할까??

 

Math.random()을 이용하여 손쉽게 랜덤한 위치에 만들 수 있다.

코드로 확인 해 보면

    const newDiv = document.createElement('div');
    
    const x = Math.random() * (fieldRect.width - 0) + 0;
    const y = Math.random() * (fieldRect.height - 0) + 0;
    
    newDiv.style.position = 'absolute';
    newDiv.style.left = `${x}px`;
    newDiv.style.top = `${y}px`;
    
    newDiv.style.width = `${30}px`; 
    newDiv.style.height = `${30}px`;
    newDiv.style.backgroundColor = 'blue';
    field.appendChild(newDiv);

x 와 y의 범위를 정해 준뒤 Math.random()으로 랜덤한 x값과 y값을 만든 후 생성된 div의 left와 top로 설정하게되면 손쉽게 랜덤위치에 div를 생성 가능하다.

 

해당 코드는 중복이 많기에 중복되는부분을 따로 함수로 만들어 사용하면 재사용성도 늘어나 더 효율적인 코드가 될 수 있다.

function createDiv(className, count) {
  const xMin = 0;
  const yMin = 0;
  const xMax = fieldRect.width;
  const yMax = fieldRect.height;
  
  for (let i = 0; i < count; i++) {
    const initGame = document.createElement('div');
    
	const x = randomNumber(xMin, xMax);
    const y = randomNumber(yMin, yMax);
    
    newDiv.style.position = 'absolute';
    newDiv.style.left = `${x}px`;
    newDiv.style.top = `${y}px`;
    
    newDiv.style.width = `${30}px`; 
    newDiv.style.height = `${30}px`;
    newDiv.style.backgroundColor = 'blue';
    field.appendChild(newDiv);
  }
}

function randomNumber(min, max) {
  return Math.random() * (max - min) + min;
}

이런식으로 함수로 만들어 두면 몇번이고 div를 계속 생성이 가능하다.