본문 바로가기
HTML,CSS,JavaScript

자바스크립트로 풍선 애니메이션 구현하기 복습

by 코딩하는아재냥 2022. 6. 25.

수업시간에 배운내용 토대로 복습겸 정리하였습니다.

JS

let banner = document.getElementById('banner'),
    img = banner.getElementsByTagName('img'),
    toggle = document.getElementById('toggle'),
    sound_btn = document.getElementById('sound_btn')

//배너의 높이값 변수
let banner_height = getComputedStyle(banner).height;
// banner의 적용된 css 중에 height;
let cast = [];
// 각각의 풍선에 대한 객체를 배열의 형태로 담을 것이다. 떨어지는 방식 랜덤으로 주기위해서 각각의 인덱스에 함수 적용예정 풍선 객체 생성
// 함수
function set_balloon(num) {
    //풍선의 속성값을 랜덤으로 생성
    let x = Math.floor(Math.random() * (500 - 10) + 10) //최대 490 최소 10
    let y = Math.floor(MAth.random() * (400 - 120) + 120)
    let size = Math.floor(Math.random() * (200 - 120))
    let angle = Math.floor(Math.random() * (360 - 0) + 0)
    let speed = Math.floor() * (2 - 0) + 0;

    //풍선 객체
    cast[num] = {
        x: x,
        y: -y,
        size: size,
        angle: angle,
        speed: speed
    };
}

//풍선 객체 초기화 함수
function ball_init(){


    for(let i=0;i<img.length;i++){
        //풍선 객체들의 속성 초기화
        set_balloon(i);
        img[i].style.left = '-5000px';
        img[i].style.top = '-5000px';
        //초기값을 모든 풍선을 왼쪽 위 멀리멀리보내서 화면에 안보이게할것이다.
    }
}

//풍선 애니메이션 함수
function animate_balloon(){
    for(let i=0;i<img.length;i++){
        //멀리 보내버렸던 초기값 풍선 속성 변경
        img[i].style.left = cast[i].x +'px';
        img[i].style.right = cast[i].y + 'px';
        img[i].style.transform = 'rotate('+cast[i].angle+')';

        //풍선 내려가고 다시 올라가고 반복하게 만들어야댐.
        if(cast[i].y<parseInt(banner_height)){
            //풍선이 화면 안에서 내려가고있을때 속도 설정
            cast[i].y += cast[i].speed;
            cast[i].angle +=cast[i].speed;
        }else{
            //풍선이 화면밖으로 나가면 초기값으로 변경
            set_balloon();
        }
    }//end for
}//end move_balloon()

//오디오 함수
function bgm_init(){
    let bgm = new Audio(); // 오디오 객체 생성
    bgm.src = 'images/bgm.mp3';
    bgm.loop = true;
    document.body.appendChild(bgm)//문서에 오디오 객체 추가

}

//메인
ball_init();
setInterval(function(){
    animate_balloon();
},1000/30);
bgm_init();

// 사운드 버튼 이벤트 핸들러
sound_btn.onclick = function(event){
    let attr = sound_btn.getAttribute('class');
    let bgm = document.getElementsByTagName('audio');

    if(attr == 'active'){
        //사운드 끔
        sound_btn.removeAttribute('class');
        sound_btn.setAttribute('src','images/sound_off.png'); //사운드 끄면 버튼이미지가 꺼진걸로 바뀜
        bgm[0].pause();
    }else{
        //사운드켬
        sound_btn.setAttribute('class','active');
        sound_btn.setAttribute('src','images/sound_on.png');
        bgm[0].play();
    }
    event.stopPropagation();
}

// 배너 열고닫기 버튼 이벤트 핸들러
toggle.onclick = function(){
    let attr = banner.getAttribute('class');

    if(attr == 'active'){
        // 배너 닫기
        banner.removeAttribute('class');
        toggle.innerHTML = '배너 열기';
        return false;
    }else{
        //배너 열기
        banner.setAttribute('class','active');
        toggle.innerHTML = '배너닫기';
        return false;
    }
};

//  배너 링크 처리
banner.onclick = function(){
}

CSS

*{ margin: 0; }
   body{
      padding: 300px 50px;
      /*background: #999; */
   }
   #banner_wrap{
      position: relative;
      width: 600px;
   }

   /* 배너 표시 상태 */
   #banner.active{
       height: 190px;
       border: 1px solid #ccc;
   }

   /* 배너 비표시 상태 */  
   #banner{
       width:600px;
       height: 0px;
       position: relative;
       overflow: hidden;
       background: url('images/bg.png');
       border-bottom: 1px solid #666;
       border-top: 1px solid #ccc;
       box-sizing: border-box;
       transition-duration: 0.5s;
   }
   #banner:hover{
      cursor: pointer;
   }
   #banner img{
       display: block;
       position: absolute;
   }

   /* 사운드 on/off 버튼 */
   #sound_btn{
      position: absolute;
      left: 10px; bottom: 10px;
      outline: none;
   }

   /* 배너 닫기/열기 버튼 */
   #toggle{
      position: absolute;
      right: 0;
      bottom: -18px;
      background: #666;
      color: white;
      font-size: 12px;
      line-height: 18px;
      padding: 0 5px;
      text-decoration: none;
   }
   #toggle:hover{ text-decoration: underline; }
   

HTML

<div id="banner_wrap">
            <figure id='banner' class="active">
                <!-- 스프라이트 이미지 -->
                <img src='images/balloon1.png' alt='h'>
                <img src='images/balloon2.png' alt='e'>
                <img src='images/balloon3.png' alt='l'>
                <img src='images/balloon4.png' alt='l'>
                <img src='images/balloon5.png' alt='o'>
                <img src='images/balloon1.png' alt='h'>
                <img src='images/balloon2.png' alt='e'>
                <img src='images/balloon3.png' alt='l'>
                <img src='images/balloon4.png' alt='l'>
                <img src='images/balloon5.png' alt='o'>
                <input id='sound_btn' type='image' src='images/sound_off.png' alt='sound'>
            </figure>
            <a id="toggle" href="#">배너 닫기</a>
        </div>
       
        <script src="main.js"></script>

댓글