반응형

마우스를 피해 움직이는 요소 구현 예시
사랑은 늘 도망가...

코드 예시

 


CSS 코드


      
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.container {
text-align: center;
}
.box {
width: 300px;
height: 300px;
background-color: white;
border: 2px solid #333;
position: relative;
overflow: hidden;
}
.heart {
font-size: 2rem;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
transition: top 0.3s ease, left 0.3s ease;
}

transition을 사용해 하트가 미끄러지듯 움직이는 것처럼 보이게 구현했다.


Java Script 코드


      
document.addEventListener('DOMContentLoaded', function() {
const heart = document.getElementById('heart');
const box = document.querySelector('.box');
heart.addEventListener('mouseover', moveHeart);
function moveHeart() {
const boxRect = box.getBoundingClientRect();
const heartRect = heart.getBoundingClientRect();
console.log(boxRect)
const maxX = boxRect.width - heartRect.width;
const maxY = boxRect.height - heartRect.height;
// 기존 위치에서 이동할 거리의 최대 값을 200px로 설정
let offsetX = Math.random() * 200 - 100;
let offsetY = Math.random() * 200 - 100;
// 새로운 위치 계산
let newX = heartRect.left - boxRect.left + offsetX;
let newY = heartRect.top - boxRect.top + offsetY;
// 새로운 위치가 경계를 넘을 경우 가운데로 이동
if (newX < 0 || newX > maxX || newY < 0 || newY > maxY) {
newX = maxX / 2;
newY = maxY / 2;
}
heart.style.left = `${newX}px`;
heart.style.top = `${newY}px`;
}
});

mouseover를 사용해 하트에 마우스를 올릴 때마다 이벤트가 발생하도록 했다.

상자와 하트의 위치 정보는 Element.getBoundingClientRect()를 사용했다.

아래는 boxRect를 console.log로 출력했을때의 결과이다. 반환된 DOMRect를 확인할 수 있을 것이다.

필요한 요소를 꺼내 사용하면 되겠다.

getBoundingClientRect 예시

이 위치 정보를 활용해 하트가 박스 안에서만 움직일 수 있도록 구현할 것이다.

 


      
const maxX = boxRect.width - heartRect.width;
const maxY = boxRect.height - heartRect.height;
let offsetX = Math.random() * 200 - 100;
let offsetY = Math.random() * 200 - 100;
let newX = heartRect.left - boxRect.left + offsetX;
let newY = heartRect.top - boxRect.top + offsetY;
if (newX < 0 || newX > maxX || newY < 0 || newY > maxY) {
newX = maxX / 2;
newY = maxY / 2;
}

Math.random()을 활용해 하트의 움직임에 변칙성을 주었다.

 

그리고 하트가 선에 닿을 경우 박스의 가운데로 이동시켜 하트가 튕기듯 움직이는 것처럼 보이게 만들었다.

이를 통해 하트가 자꾸 상자의 선을 넘어가버리는 현상을 방지했다.


      
heart.style.left = `${newX}px`;
heart.style.top = `${newY}px`;

위에서 구한 위치를 하트의 left와 top에 넣어주기만 하면 하트가 계산된 위치로 이동하게 된다.

반응형
그레이트현