HTML5/Natural Decrement

Natural Decrement in Ball Animation

Soul-Learner 2014. 7. 2. 15:33

볼 애니메이션(Ball Animation)에서 속도의 자연감소 효과 구현 예


<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>HTML5 원 그리기</title>

<style type="text/css">

canvas { border:5px solid black;}

</style>

<script type="text/javascript">


var x = 30;

var y = 30;

var r = 20;

var xspeed = 3.0;

var yspeed = 3.0;

//var prevTime = 0;


function drawArc() {

var c = document.getElementById("canvas1");

if(!c.getContext) {

alert('Canvas그리기를 지원하는 웹브라우저가 아닙니다');

return;

}

var ctx = c.getContext("2d");

ctx.clearRect(0,0,c.width,c.height);

x += xspeed;

y += yspeed;

ctx.beginPath();

ctx.arc(x,y,r, 0, (Math.PI/180)*360);

ctx.strokeStyle='rgb(0,0,0)';

ctx.stroke();

if((x-r)<=0) {//왼쪽끝

x=r;

xspeed *= -1

}else if((y-r)<=0) {//상단

y=r;

yspeed *= -1

}else if((x+r)>=c.width) {

x = c.width-r;

xspeed *= -1

}else if((y+r)>=c.height) {

y = c.height-r;

yspeed *= -1

}

xspeed *= 0.992;

yspeed *= 0.992;

//console.log("xspeed:"+xspeed+", yspeed:"+yspeed);

if(Math.abs(xspeed)<0.03 && Math.abs(yspeed)<0.03) stopBall();

/*

var now = Date.now();

console.log(now-prevTime);

prevTime = now;

*/

}


var intval;

function moveBall() {

intval = setInterval(function(){drawArc();}, 30);

}

function stopBall() {

clearInterval(intval);

alert("Ball Stopped!");

}


</script>

</head>

<body>

<canvas id="canvas1" width="300" height="200"></canvas>

<p>

<input type="button" value="START" onclick="moveBall();">

<input type="button" value="STOP" onclick="stopBall();">

</body>

</html>