본문 바로가기

JavaScript/소스 코드

[JavaScript] 공튀기기

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="utf-8">
        <title>공튀기기</title>
        <style>
            canvas{
                border: 1px solid gray;
            }
        </style>
    </head>
    <body>
        <canvas id="can">
        </canvas>
        <script>
            var canvas=document.getElementById("can");
            var ctx=canvas.getContext("2d");
            canvas.width=600;
            canvas.height=600;
            
            var x = 20; // 공의 x좌표
            var vx = 2; // 공의 x rkthreh
            var y = 20; // 공의 y좌표 
            var vy = 5; // 공의 y 가속도
            // 공의 가속도를 이용해서 각도와 속도를 조절할 수 있다.
            
            var r = 20; // 공의 반지름
            
            ctx.beginPath();
            ctx.arc(x,y,20,0,Math.PI*2,false);
            ctx.fillStyle="crimson";
            ctx.fill();
            ctx.beginPath();
            
            //setInterval(function, 시간);
            //시간/1000 초마다 해당 함수를 실행한다.
            
            function box_check(){
                if(y>(canvas.height-r)||y<r){
                    vy*=-1;
                }
                if(x>canvas.width-r||x<r){
                    vx*=-1;
                }
            } //공과 박스의 상호작용
            
            function move(){
                ctx.beginPath();
                ctx.clearRect(0,0,canvas.width, canvas.height);
                ctx.arc(x,y,r,0,Math.PI*2,false);
                ctx.fillStyle="crimson";
                ctx.fill();
                ctx.closePath();
                x += vx;
                y += vy;
                box_check();  
            }
            
            setInterval(move, 20);
        </script>
    </body>
</html>