JAVASCRIPT

게임 이펙트 첫번째 !

Kim do hyun 2023. 4. 24. 18:27
728x90
반응형

게임 이펙트 

폴더를 클릭하면 폴더 색깔별로 헤더의 색깔이 바뀌고 현재 시각이 우측 상단에 나오는 게임 이펙트 메인 화면입니다.

 

 

 

HTML

<body>
    <div class="cursor">
        <img src="img/game_mouse01.png" alt>
    </div>
    <header id="header">
        <h1>WEBS GAME WORLD</h1>
        <div id="time">2023년 4월 24일 09시 30분 15초</div>
    </header>

    <main>
        <div class="icon__box">
            <div class="icon1">
                <img src="img/game_icon01.png" alt="뮤직">
                <span>뮤직 듣기</span>
            </div>
            <div class="icon2">
                <img src="img/game_icon02.png" alt="뮤직">
                <span>뮤직 듣기</span>
            </div>
            <div class="icon3">
                <img src="img/game_icon03.png" alt="뮤직">
                <span>뮤직 듣기</span>
            </div>
            <div class="icon4">
                <img src="img/game_icon04.png" alt="뮤직">
                <span>뮤직 듣기</span>
            </div>
        </div>
    </main>
    
    <footer id="footer">
        <div class="info">현재 맥을 사용하고 있으면, 확인 크기는 1920 X 760 입니다.</div>
    </footer>

GSAP

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"></script>
window.onload = function(){
    window.addEventListener("mousemove", e => {
        gsap.to(".cursor", {
            duration: 0,
            left: e.pageX - 5,
            top: e.pageY -10
        })
    });

    printTime();    // 오른쪽 상단 시간
    printAgent();    // 하단 중앙
}

코드 설명

이 코드는 GreenSock Animation Platform (GSAP)를 사용하여 커서를 마우스 포인터의 위치로 움직이는 효과를 만드는 JavaScript 코드입니다.

window.onload 함수는 문서의 모든 리소스가 로드되면 실행됩니다. 여기서는 mousemove 이벤트 리스너를 등록하여 마우스가 움직일 때마다 gsap.to() 메소드를 호출합니다.

gsap.to()는 GSAP에서 제공하는 애니메이션 함수로, 첫 번째 인자는 애니메이션 대상의 CSS 선택자입니다. 이 경우 .cursor 클래스가 대상입니다.

두 번째 인자는 애니메이션 옵션 객체입니다. 여기서는 duration, left, top 속성을 설정했습니다. duration은 애니메이션 지속 시간을 나타내며, 0으로 설정하여 마우스 이동 시 즉시 커서 위치가 변경되도록 합니다. left와 top 속성은 커서의 CSS left와 top 속성 값을 마우스 포인터의 현재 위치 값으로 설정합니다.

그리고 마지막으로 printTime()과 printAgent() 함수가 호출됩니다.

JQUERY

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<script>
    $(".icon1").draggable({
        containment: ".icon__box", scroll: false,
        start: function() {
            $(".cursor img").attr("src", "img/game_mouse01.png");
            $("#header").css("background-color","red");
        },
    });
    $(".icon2").draggable({
        containment: ".icon__box", scroll: false,
        start: function() {
            $(".cursor img").attr("src", "img/game_mouse02.png");
            $("#header").css("background-color","blue");
        },
    });
    $(".icon3").draggable({
        containment: ".icon__box", scroll: false,
        start: function() {
            $(".cursor img").attr("src", "img/game_mouse03.png");
            $("#header").css("background-color","green");
        },
    });
    $(".icon4").draggable({
        containment: ".icon__box", scroll: false,
        start: function() {
            $(".cursor img").attr("src", "img/game_mouse04.png");
            $("#header").css("background-color","yellow");
        },
    });

    function displayCurrentDateTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1; // getMonth()는 0부터 11까지의 값을 반환하므로 1을 더해줍니다.
    const date = now.getDate();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds();
    const dateTimeString = `${year}년 ${month}월 ${date}일 ${hours}시 ${minutes}분 ${seconds}초`;
    document.getElementById("time").innerHTML = dateTimeString;
  }

  // 페이지가 로드될 때마다 1초마다 현재 날짜와 시간을 업데이트합니다.
  setInterval(displayCurrentDateTime, 1000);

코드 설명

첫 번째 스크립트 태그는 jQuery 라이브러리를 로드합니다. 두 번째 스크립트 태그는 jQuery UI 라이브러리를 로드합니다. jQuery UI는 드래그 앤 드롭 기능과 같은 인터랙티브한 기능을 제공합니다.

$(".icon1"), $(".icon2"), $(".icon3"), $(".icon4")"는 jQuery의 클래스 선택자로, 각각 아이콘1, 아이콘2, 아이콘3, 아이콘4를 가리킵니다. draggable() 메소드를 사용하여 해당 요소를 드래그 가능한 요소로 만듭니다. containment 옵션은 드래그가 가능한 범위를 지정하며, .icon__box 클래스 요소로 설정합니다. scroll 옵션은 스크롤 이동 여부를 결정합니다.

start 콜백 함수는 드래그가 시작될 때 호출됩니다. 각각의 드래그 가능한 아이콘을 드래그할 때마다 $(".cursor img").attr("src", "img/game_mouse01.png");와 같이 해당 아이콘에 맞는 마우스 커서 이미지와 $("#header").css("background-color","red");와 같이 해당 아이콘에 맞는 헤더 배경색이 변경됩니다.

setInterval() 함수를 사용하여 displayCurrentDateTime() 함수를 1초마다 호출합니다. displayCurrentDateTime() 함수는 현재 날짜와 시간을 출력합니다. Date() 객체를 생성하고, getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds() 함수를 사용하여 현재 연도, 월, 일, 시간, 분, 초를 가져옵니다. 이후 문자열 템플릿 리터럴(${year}년 ${month}월 ${date}일 ${hours}시 ${minutes}분 ${seconds}초)을 사용하여 현재 날짜와 시간을 문자열로 변환하고 document.getElementById("time").innerHTML로 해당 문자열을 HTML 요소에 삽입합니다.