자바스크립트 캔버스 에니메이션 시소

행복햐 2017. 9. 5. 11:02

참고 : https://www.w3schools.com/graphics/tryit.asp?filename=trygame_rotate_game

참고 : https://codepen.io/Anwesh43/pen/QpaVEV?editors=1010

 
 


소스 코드

<style>

canvas {

    border:1px solid #d3d3d3;

    background-color: #f1f1f1;

}

</style>


<canvas id="canvas" style="width: 480; height: 270"></canvas>


<button type="button" onclick="startGame()">Click Me!</button>


<script>


var myGamePiece;


function startGame() {

    myGamePiece = new component(50, 30, "red", 80, 75);

    myGameArea.start();

}


var myGameArea = {

    canvas : document.createElement("canvas"),

    start : function() {

        this.context = canvas.getContext("2d");

        this.interval = setInterval(updateGameArea, 200);

    },

    stop : function() {

        clearInterval(this.interval);

    },    

    clear : function() {

        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

    }

}


function component(width, height, color, x, y) {

    this.width = width;

    this.height = height;

    this.angle = 0;

    this.x = x;

    this.y = y;

    this.deg = 0;

    this.dir = 1;

    this.update = function() {

        ctx = myGameArea.context;

        ctx.save();

        ctx.translate(this.x, this.y);        

        ctx.rotate(this.angle);

        ctx.fillStyle = color;

        ctx.fillRect(0, -this.height , this.width, this.height);

  //대칭으로 그리기

        ctx.scale(-1,1)

        ctx.fillRect(0, -this.height , this.width, this.height);       

        ctx.restore();    

    }

}


function updateGameArea() {


    myGameArea.clear();

    myGamePiece.deg += myGamePiece.dir*6

    if (myGamePiece.deg >=30) {

    myGamePiece.dir = -1

    }

if (myGamePiece.deg <=-30) {

    myGamePiece.dir = 1

    }

    

    myGamePiece.angle = myGamePiece.deg * Math.PI / 180;    

    myGamePiece.update();

}


</script>