🚀 from error to study/Normal

[티스토리] JS, CSS로 따라오는 마우스 커서 만들기

천재강쥐 2024. 11. 11. 09:53

 

 

 

🔥 포스팅 계기

 

여느 때와 같이 구글링 중에 어느 블로그에서 마우스 커서를 따라다니는 애니메이션을 봄
내 야구공 커서에 접목시켜서 티스토리 야구방 만들면 재미있겠는데...?

 

 

 

 

📍 구현법

👉🏻 검색해 보니 리액트로 구현하는 방법도 있는 것 같은데 나는 리액트를 모름

👉🏻 바닐라 자바스크립트와 css로만 구현하고, 티스토리 스킨 편집에서 적용하기로 함

 

 

 

📍 구현 전 참고

👉🏻 먼저 나는 티스토리에 이미 적용해 놓은 나만의 js가 있음

👉🏻 블로그 관리 > 스킨 편집 > html 편집 접속하여 html/css에 직접 적용해도 상관은 없으나 이것저것 별도 커스텀을 하고 싶다면 나처럼 js 파일을 하나 빼 놓는 걸 추천함

 

 

 

📍 CSS 코드

👉🏻마우스 커서를 설정하는 부분

👉🏻 원래 마우스 커서는 야구공이었는데 이걸 타자 모양으로 바꾸고 공이 날아오도록 애니메이션을 줄 것임

👉🏻 왜냐? 그것이 야구니까 (끄덕)

/* 마우스 커서 start */
/* 야구공 https://www.cursors-4u.com/cursor/2005/08/27/spo33.html */
/* 타자 https://www.cursors-4u.com/cursor/2009/02/27/baseball-player.html */
/* Start https://www.cursors-4u.com */ * {cursor: url(https://cur.cursors-4u.net/sports/spo-4/spo383.cur), auto !important;} /* End https://www.cursors-4u.com */
/* 마우스 커서 end*/

 

 

 

 

📍 JS 코드

👉🏻마우스 커서를 따라다니는 애니메이션을 설정하는 부분

👉🏻 페이지 로드되고 나면 addCursorStyle(커서 스타일 추가), insertCursorAnimation(커서 애니메이션 추가) 메소드를 부름

const insertCursorAnimation = () => {
	console.log("Adding cursor animation!");
	
	// 커서 요소를 생성하여 body에 추가
	const cursor = document.createElement("div");
	cursor.classList.add("cursor");
	document.body.appendChild(cursor);

	// 마우스 움직임에 따라 커서 위치를 업데이트
	document.addEventListener("mousemove", (event) => {
		cursor.style.transform = `translate(${event.pageX + 25}px, ${event.pageY - 7}px)`;
	});

	console.log("Cursor animation added");
}

// 스타일 추가
const addCursorStyle = () => {
	const style = document.createElement("style");
	style.innerHTML = `
		.cursor {
			position: absolute;
			top: 0;
			left: 0;
			width: 30px;
			height: 30px;
			background: url("https://cur.cursors-4u.net/sports/spo-1/spo33.png") no-repeat center;
			background-size: cover;
			pointer-events: none;
			transition: transform 1.0s ease-out; /* 부드럽고 느린 따라오는 효과 */
			z-index: 9999; /* 최상위 요소로 설정 */
		}
	`;
	document.head.appendChild(style);
};

window.addEventListener("load", () => {
	console.log("load Script Started!");
	
	addCursorStyle(); // 커서 스타일 추가
	insertCursorAnimation();  // 커서 애니메이션 추가
	
	console.log("load Script Finished!");
});

 

 

 

 

📍 결과

👉🏻 짠! 배팅 애버리지 쭉쭉 상승시키는 야구 커서 애니메이션 적용 완료