본문 바로가기

WEB_TECH/HTML5

canvas animation 예제입니다.

캔바스에 공을 움직여 벽에 부딪히면 방향이 바뀌는 애니메이션을 만들어 보겠습니다.


<!doctype html>

<html>

<head>

<meta charset="euc-kr">

<title>canvas animation</title>


</head>


<body>

<canvas id="a_canvas" width="300" height="300"></canvas>

<script type="text/javascript">

var canvas = document.getElementById("a_canvas");

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


//공의 상태

var ball = {x:10, y:100, dx:2, dy:2};


//움직이기

setInterval(drawBall, 30);

function drawBall(){

var i;

//배경 그리기

console.log("호출");

context.fillStyle = "blue";

context.fillRect(0,0,300,300);

//공 그리기

context.beginPath();

context.arc(ball.x, ball.y, 5, 0, 2*Math.PI, true);

context.fillStyle = "red";

context.fill();

//공 이동 시키기

ball.x += ball.dx;

ball.y += ball.dy;

if(ball.x-5 < 0 || ball.x+5 > 300){

ball.dx *= -1;

}

if(ball.y-5 <0 || ball.y+5 > 300){

ball.dy *= -1;

}

}

</script>

</body>

</html>