Canvas - 11

이강민·2022년 1월 11일
0

[혼공]Canvas

목록 보기
11/12
post-thumbnail

고급 애니메이션

간단한 물리동작 추가

캔버스에 공그리기

        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        //Ball을 여러개 호출할 수도 있으니 난 클래스로 만들어 관리하겠다. 
        class Ball{
            //Ball의 객체를 생성함
            constructor() {
                //x의 값은 100
                this.x = 100;
                //y의 값은 100
                this.y = 100;
                //radius의 값은 100
                this.radius = 25;
                //color의 값은 100
                this.color = 'blue';
            }    
            //메소드를 만들어 draw함수를 관리한다.
            draw(){
                 ctx.beginPath();
                 ctx.arc(this.x, this.y, this.radius, 0, Math.PI *2, true);
                 ctx.closePath();
                 ctx.fillStyle = this.color;
                 ctx.fill();
             } 
        }
        //ball을 생성하고 
        let ball = new Ball();
        //ball의 draw를 호출하면 this 객체를 받은 애니메이션이 그려진다. 
        ball.draw();

속도 추가하기

        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        let play;
        //Ball을 여러개 호출할 수도 있으니 난 클래스로 만들어 관리하겠다. 
        class Ball{
            //Ball의 객체를 생성함
            constructor() {
                //x의 값은 100
                this.x = 100;
                //y의 값은 100
                this.y = 100;
                //radius의 값은 100
                this.radius = 25;
                //color의 값은 100
                this.color = 'blue';
                this.speed = 0.5;
            }    
            //메소드를 만들어 캔버스에 drawing 함
            blueprint(){
                 ctx.beginPath();
                 ctx.arc(this.x, this.y, this.radius, 0, Math.PI *2, true);
                 ctx.closePath();
                 ctx.fillStyle = this.color;
                 ctx.fill();
             } 
        }
        function draw(){
            //캔버스의 크기와 높이 만큼 지운다.
            ctx.clearRect(0,0,canvas.width, canvas.height);
            //ball의 blueprint 함수를 실행한다.
            ball.blueprint();
            ball.x += ball.speed;
            ball.y += ball.speed;
            //밀리초단위로 ball.speed만큼 x,y가 증가한다.
            console.log(ball.x, ball.y);
            play = window.requestAnimationFrame(draw);
        }
        //ball을 생성하고 
        let ball = new Ball();
        //ball의 객체를 확인 할 수 있다. 
        console.log(ball)
        //draw 함수를 살펴보자, 함수 실행 코드

        //마우스를 올리면 함수가 더 실행되며, 결과적으로 속도 증가됨
    
        canvas.addEventListener('mouseover',function(e){
            play = window.requestAnimationFrame(draw);
        })
        
        //마우스를 내리면 paly 애니메이션을 종료하기 때문에 속도가 빠짐
        canvas.addEventListener('mouseout', function(e){
            window.cancelAnimationFrame(play)
        })
        
        draw();

경계만들기

        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        let play;
        //Ball을 여러개 호출할 수도 있으니 난 클래스로 만들어 관리하겠다. 
        class Ball{
            //Ball의 객체를 생성함
            constructor() {
                //x의 값은 100
                this.x = 100;
                //y의 값은 100
                this.y = 100;
                //radius의 값은 100
                this.radius = 25;
                //color의 값은 100
                this.color = 'blue';
                this.speedX = 2;
                this.speedY = 2;
            }    
            //메소드를 만들어 캔버스에 drawing 함
            blueprint(){
                 ctx.beginPath();
                 ctx.arc(this.x, this.y, this.radius, 0, Math.PI *2, true);
                 ctx.closePath();
                 ctx.fillStyle = this.color;
                 ctx.fill();
             } 
        }
        function draw(){
            //캔버스의 크기와 높이 만큼 지운다.
            ctx.clearRect(0,0,canvas.width, canvas.height);
            //ball의 blueprint 함수를 실행한다.
            ball.blueprint();
            ball.x += ball.speedX;
            ball.y += ball.speedY;
            //밀리초단위로 ball.speed만큼 x,y가 증가한다.
            console.log(ball.x, ball.y);
            //경계를 만들어 보자
            //볼의 y위치 + 볼의 y스피드가 캔버스의 높이 - 볼의 크기 + 오차범위 보다 크거나 볼의 y위치 + 볼의 y스피드가 볼의 크기 - 오차범위보다 작을 때 
            if(ball.y + ball.speedY > canvas.height - ball.radius+5 || ball.y + ball.speedY < ball.radius - 5){
                //볼의 방향을 바꿈, 
                ball.speedY = -ball.speedY
            }
            if(ball.x + ball.speedX > canvas.width - ball.radius+5 || ball.x + ball.speedX < ball.radius-5){
                ball.speedX = -ball.speedX
            }
            play = window.requestAnimationFrame(draw);
        }
        //ball을 생성하고 
        let ball = new Ball();
        //ball의 객체를 확인 할 수 있다. 
        //console.log(ball)

        canvas.addEventListener('mouseout', function(e){
            window.cancelAnimationFrame(play)
        })
        canvas.addEventListener('mouseover', function(e){
            play = window.requestAnimationFrame(draw)
        })

        //draw 함수를 살펴보자, 함수 실행 코드
        //draw();

중력에 의한 튀는 높이 감소시키기

 //볼의 Y축을 점차 감소시키면서 공이 아래에 튀기는 것을 표현할수 있다.
            ball.speedY *= .99;
            ball.speedY += .15;

후행효과(블러)

        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        let play;
        //Ball을 여러개 호출할 수도 있으니 난 클래스로 만들어 관리하겠다. 
        class Ball{
            //Ball의 객체를 생성함
            constructor() {
                //x의 값은 100
                this.x = 200;
                //y의 값은 100
                this.y = 200;
                //radius의 값은 100
                this.radius = 25;
                //color의 값은 100
                this.color = 'blue';
                this.speedX = 5;
                this.speedY = 2;
            }    
            //메소드를 만들어 캔버스에 drawing 함
            blueprint(){
                 ctx.beginPath();
                 ctx.arc(this.x, this.y, this.radius, 0, Math.PI *2, true);
                 ctx.fillStyle = this.color;
                 ctx.closePath();
                 ctx.fill();
             } 
            }
            //ball을 생성하고 
            let ball = new Ball();
            //ball의 객체를 확인 할 수 있다. 
            //console.log(ball)
        function draw(){
            //지우는 대신에 fillRect를 하여 스타일을 흰색에 투명도를 주면 원을 그리면서 투명도를 주기때문에 쉽게 후행효과를 줄 수 있다. fillRect도 덮어씌여지면서 투명도가 1이되어 그 뒤쪽이 보이지 않는 것이다. 
            ctx.fillStyle = 'rgba(255,255,255,0.2)';
            ctx.fillRect(0,0,canvas.width, canvas.height);
            //캔버스의 크기와 높이 만큼 지운다.
            //ctx.clearRect(0,0,canvas.width, canvas.height);
            //ball의 blueprint 함수를 실행한다.
            ball.blueprint();
            ball.x += ball.speedX;
            ball.y += ball.speedY;
            //볼의 Y축을 점차 감소시키면서 공이 아래에 튀기는 것을 표현할수 있다.
            //ball.speedY *= .99;
            //ball.speedY += .15;

            //밀리초단위로 ball.speed만큼 x,y가 증가한다.
            console.log(ball.speedX, ball.speedY);
            //경계를 만들어 보자
            //볼의 y위치 + 볼의 y스피드가 캔버스의 높이 - 볼의 크기 + 오차범위 보다 크거나 볼의 y위치 + 볼의 y스피드가 볼의 크기 - 오차범위보다 작을 때 
            if(ball.y + ball.speedY > canvas.height - ball.radius+5 || ball.y + ball.speedY < ball.radius - 5){
                //볼의 방향을 바꿈, 
                ball.speedY = -ball.speedY
            }
            if(ball.x + ball.speedX > canvas.width - ball.radius+5 || ball.x + ball.speedX < ball.radius-5){
                ball.speedX = -ball.speedX
            }
            play = window.requestAnimationFrame(draw);
        }

        canvas.addEventListener('mouseover', function(e){
            play = window.requestAnimationFrame(draw)
        })
        canvas.addEventListener('mouseout', function(e){
            window.cancelAnimationFrame(play)
        })

        //draw 함수를 살펴보자, 함수 실행 코드
        ball.blueprint();

마우스컨트롤 추가하기

        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        let play;
        //flag를 하나 만들어 사용할 것이다.
        let running = false;
        //Ball을 여러개 호출할 수도 있으니 난 클래스로 만들어 관리하겠다. 
        class Ball{
            //Ball의 객체를 생성함
            constructor() {
                //x의 값은 100
                this.x = 100;
                //y의 값은 100
                this.y = 100;
                //radius의 값은 100
                this.radius = 25;
                //color의 값은 100
                this.color = 'blue';
                this.speedX = 5;
                this.speedY = 1;
            }    
            //메소드를 만들어 캔버스에 drawing 함
            blueprint(){
                 ctx.beginPath();
                 ctx.arc(this.x, this.y, this.radius, 0, Math.PI *2, true);
                 ctx.fillStyle = this.color;
                 ctx.closePath();
                 ctx.fill();
             } 
            }
            //ball을 생성하고 
            let ball = new Ball();
            //ball의 객체를 확인 할 수 있다. 
            //console.log(ball)
        //다른 곳에 사용하기 위해 후행효과 함수를 분리한다
        function clear(){
            //지우는 대신에 fillRect를 하여 스타일을 흰색에 투명도를 주면 원을 그리면서 투명도를 주기때문에 쉽게 후행효과를 줄 수 있다. fillRect도 덮어씌여지면서 투명도가 1이되어 그 뒤쪽이 보이지 않는 것이다. 
            ctx.fillStyle = 'rgba(255,255,255,0.2)';
            ctx.fillRect(0,0,canvas.width, canvas.height);
        }
        function draw(){
            clear();
            //캔버스의 크기와 높이 만큼 지운다.
            //ctx.clearRect(0,0,canvas.width, canvas.height);
            //ball의 blueprint 함수를 실행한다.
            ball.blueprint();
            ball.x += ball.speedX;
            ball.y += ball.speedY;
            //볼의 Y축을 점차 감소시키면서 공이 아래에 튀기는 것을 표현할수 있다.
            //ball.speedY *= .99;
            //ball.speedY += .15;

            //밀리초단위로 ball.speed만큼 x,y가 증가한다.
            console.log(ball.speedX, ball.speedY);
            //경계를 만들어 보자
            //볼의 y위치 + 볼의 y스피드가 캔버스의 높이 - 볼의 크기 + 오차범위 보다 크거나 볼의 y위치 + 볼의 y스피드가 볼의 크기 - 오차범위보다 작을 때 
            if(ball.y + ball.speedY > canvas.height || ball.y + ball.speedY < 0){
                //볼의 방향을 바꿈, 
                ball.speedY = -ball.speedY
            }
            if(ball.x + ball.speedX > canvas.width  || ball.x + ball.speedX < 0){
                ball.speedX = -ball.speedX
            }
            play = window.requestAnimationFrame(draw);
        }
        
        canvas.addEventListener('mousemove', function(e){
            //running이 false 일때 
            if(!running){
                //새롭게 그린다.
                clear();
                //x,y는 마우스가 움직이는 대로 변경된다. 상수는 마우스가 중간에 오도록 조절한 것이다.
                ball.x = e.clientX - 100;
                ball.y = e.clientY -80;
                // 원을 새롭게 그린다. 
                ball.blueprint();
            }
        })
        canvas.addEventListener('click', function(e){
            if(!running){
                //클릭하면 애니메이션을 그리고 running을 true로 만들어 mouseover 이벤트가 동작하지 않도록 한다.
                play = window.requestAnimationFrame(draw);
                running = true;
            }
        })
        canvas.addEventListener('mouseout', function(e){
            //마우스가 캔버스에서 나가면 애니메이션을 정지하고, running을 다시 false로 하여 마우스가 다시 들어왔을때 mouseover 이벤트를 실행하게 만든다.
            window.cancelAnimationFrame(play)
            running = false;
        })

        //blueprint 함수를 살펴보자, 함수 실행 코드
        ball.blueprint();
profile
배움은 끝없이

0개의 댓글