Last active
December 20, 2016 14:14
-
-
Save hanjae-jea/1fd19c5d6ed16064a305c443f0acf3fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<title>벽돌깨기</title> | |
<script type="text/javascript"> | |
var myBody = null; | |
var canvas = null; | |
var context = null; | |
var width_canvas = 0; | |
var height_canvas = 0; | |
var movement = 5; | |
var ballC = 4; // 캔버스 위에 있는 공의 수 | |
var x = [], y = [], angle = []; | |
// 각 공의 x좌표, y좌표, 각도 | |
function initBrick() | |
{ | |
canvas = document.getElementById("canvas"); | |
context = canvas.getContext("2d"); | |
myBody = document.getElementById("myBody"); | |
width_canvas = canvas.width; | |
height_canvas = canvas.height; | |
for( var i = 0 ; i < ballC ; i ++ ){ | |
context.beginPath(); | |
x[i] = width_canvas * Math.random(); // 공의 시작위치도 캔버스 안 임의의 지점에서 시작하게 한다. | |
y[i] = height_canvas * Math.random(); | |
context.arc(x[i], y[i], 12, 0, 360*Math.PI/180, false); | |
context.closePath(); | |
context.fill(); | |
// 각 공이 움직이는 각도를 랜덤하게 설정한다. | |
angle[i] = (Math.PI*2)*Math.random(); | |
// 만약에 튕기는 각도가 0~3도 여서 문제가 생기는 경우 | |
while( (Math.PI*2-angle[i])*(Math.PI*2-angle[i]) < 0.5 ){ | |
angle[i] = (Math.PI*2)*Math.random(); | |
} | |
} | |
} | |
function drawCanvas() | |
{ | |
context.clearRect(0, 0, width_canvas, height_canvas); | |
context.beginPath(); | |
for( var i = 0 ; i < ballC ; i ++ ){ | |
// 다음 프레임에 각 공이 위치할 좌표를 계산한다. | |
var qx = x[i] + Math.round(Math.cos(angle[i])*movement); | |
var qy = y[i] + Math.round(Math.sin(angle[i])*movement); | |
// 만약 공의 위치가 캔버스 밖을 벗어나는 경우 | |
if( qx <= 0 || width_canvas <= qx ){ | |
angle[i] = Math.PI - angle[i]; // 각도를 y축 대칭 회전시킨다. | |
} if( qy <= 0 || height_canvas <= qy ){ | |
angle[i] = Math.PI*2 - angle[i]; // 각도를 x축 대칭 회전시킨다. | |
} | |
while( angle[i] < 0 ) angle[i] += Math.PI*2; // 각도는 항상 [0, PI) 사이이다. | |
while( angle[i] > Math.PI*2 ) angle[i] -= Math.PI*2; | |
x[i] = qx; | |
y[i] = qy; // 실제 도형을 이동시킴. | |
context.arc(x[i], y[i], 10, 0, 360*Math.PI/180, false); | |
context.closePath(); | |
} | |
context.fill(); | |
} | |
setInterval("drawCanvas()", 14); // 1초에 60번 그려 화면에 부드럽게 움직이기 위해 14ms 단위로 반복한다. | |
</script> | |
</head> | |
<body id="myBody" onload="initBrick();"> | |
<canvas id="canvas" width="400" height="400" style="border:solid 1px #000000">canvas 사용하기</canvas> | |
<br> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment