const field = document.querySelector(".game_field");
const fieldRect = field.getBoundingClientRect();

.game_field {
  width: 100%;
  height: 55%;
  margin-top: 40px;
  position: relative;
}

function additem(className, count, imgPath) {
  const x1 = 0;
  const y1 = 0;
  **const x2 = fieldRect.width;
  const y2 = fieldRect.height;**

  for (let i = 0; i < count; i++) {
    const item = document.createElement("img");
    item.setAttribute("class", className);
    item.setAttribute("src", imgPath);
    item.style.position = "absolute";
    const x = randomNumber(x1, x2);
    const y = randomNumber(y1, y2);
    item.style.left = `${x}px`;
    item.style.top = `${y}px`;
    field.appendChild(item);
  }
}
function randomNumber(min, max) {
  return Math.random() * (max - min) + min;
}
additem("trash", TRASH_COUNT, "./img/trash.png");
additem("turtle", TURTLE_COUNT, "./img/turtle.png");

Untitled

아이템들이 생성되는데 필요한 인자들을 넘겨준다.

-className

-count

-src

🚩 item을 넣을 공간 지정해주기

📌element.getBoundingClientRect( )

left, top, right, bottom, x, y, width, height 프로퍼티로 element의 정보를 알려준다.

item들을 필드의 위치 안에서 랜덤으로 생성되게 만들면 된다.

🚩 랜덤으로 item 생성하기

📌Math.random() * (max - min) + min;

Untitled

가장 작은 수와 가장 큰 수 사이에 랜덤으로 숫자를 뽑아내는 함수이다.

left(x)값은 x1=0과 x2=width 값 사이의 랜덤한 숫자

top(y)값은 y1=0과 y2=height 값 사이의 랜덤한 숫자 를 할당한다.

❌ 문제점

Untitled

필드 밖으로 item들이 생성되었다.

아무래도 필드 width와 height 끝부분에서 생성된 아이템들이 걸쳐져서 생성된 듯 하다.

본래의 필드 크기보다 item width와 height 만큼 제외해야 필드 안에 생성될 것 같다.

.
.
const x2 = fieldRect.width **- TURTLE_WIDTH**;
const y2 = fieldRect.height **- TURTLE_HEIGHT;**
.
.

ploggingGame_random-item_Test.gif

필드 안에서만 item들이 생성된다!!