본문 바로가기
JavaScript

[JavaScript] 마우스 커서 커스터마이징하기

by dev또리 2023. 6. 16.
728x90

HTML

 

<div class="cursor rounded"></div>
<div class="cursor pointed"><div>

 

 

 

CSS

 

body{
  background-color: #1D1E22;
  cursor: none;
}

.rounded{
  width: 30px;
  height: 30px;
  border: 2px solid #fff;
  border-radius: 50%;
}

.pointed{
  width: 7px;
  height: 7px;
  background-color: white;
  border-radius: 50%;

 

 

 cursor 속성의 값을 none으로 하여 기본 커서를 안보이게 한 다음 커스텀 div 커서를 화면에 표시할 것이다.

여기서 div를 커서 처럼 보이게 스타일을 준다.

상황에 따라 배경 색을 추가하거나 이모지를 쓰는 등 스타일을 더 넣을 수도 있다.

 

 

 

 

JS

 

const cursorRounded = document.querySelector('.rounded');
const cursorPointed = document.querySelector('.pointed');


const moveCursor = (e) => {
  const mouseY = e.clientY;
  const mouseX = e.clientX;
   
  cursorRounded.style.transform = `translate3d(${mouseX}px, ${mouseY}px, 0)`;
  
  cursorPointed.style.transform = `translate3d(${mouseX}px, ${mouseY}px, 0)`;
 
}

window.addEventListener('mousemove', moveCursor);

 

 

마우스 움직임을 알아내기 위해 window 객체에 이벤트 리스너를 추가했다.

마우스가 움직이면 moveCursor() 함수가 호출되고 이 함수의 매개변수로 이벤트 객체 e를 넘긴다.

이 이벤트 객체를 통해 마우스의 좌표가 몇 인지 알 수 있다.

728x90

댓글