CHAPTER 11. 자바스크립트와캔버스로게임 만들기
캔버스 캔버스는 <canvas> 요소로생성 캔버스는 HTML 페이지상에서사각형태의영역 실제그림은자바스크립트를통하여코드로그려야한다.
컨텍스트객체 컨텍스트 (context) 객체 : 자바스크립트에서물감과붓의역할을한다. var canvas = document.getelementbyid("mycanvas"); var context = canvas.getcontext("2d");
예제 <!DOCTYPE html> <html> <body> <canvas id="mycanvas" width="200" height="100" style="border: 1px dotted red"></canvas> <script> var canvas = document.getelementbyid("mycanvas"); var context = canvas.getcontext("2d"); context.fillstyle = "#00FF00"; context.fillrect(0, 0, 100, 50); </script> </body> </html>
직선그리기예제 <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; </style> </head> <body> <canvas id="mycanvas" width="300" height="200"></canvas> <script> var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); context.beginpath(); context.moveto(0, 0); context.lineto(100, 100); context.lineto(150, 50); context.lineto(200, 100); context.stroke(); </script> </body> </html>
사각형예제 <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; </style> </head> <body> <canvas id="mycanvas" width="300" height="200"></canvas> <script> var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); context.beginpath(); context.rect(10, 10, 100, 100); context.fillstyle = "yellow"; context.fill(); </script> </body> </html>
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; </style> </head> 원예제
원예제 <body> <canvas id="mycanvas" width="300" height="200"></canvas> <script> var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); context.beginpath(); context.arc(100, 100, 80, 0, 2.0 * Math.PI, false); context.strokestyle = "red"; context.stroke(); context.beginpath(); context.arc(100, 100, 60, 0, 1.5 * Math.PI, false); context.closepath(); context.strokestyle = "blue"; context.stroke(); context.beginpath(); context.arc(100, 100, 40, 0, 1.5 * Math.PI, false); context.strokestyle = "green"; context.stroke(); </script> </body> </html>
커브예제 <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; </style> </head> <body> <canvas id="mycanvas" width="300" height="200"></canvas> <script> var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); context.beginpath(); context.moveto(90, 130); context.beziercurveto(140, 10, 288, 10, 288, 130); context.linewidth = 10; context.strokestyle = 'black'; context.stroke(); </script> </body> </html>
도형예제 <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; </style> </head> <body> <canvas id="mycanvas" width="300" height="200"></canvas> <script> var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); context.beginpath(); context.moveto(50, 100); context.lineto(75, 50); context.lineto(100, 100); context.closepath(); context.fillstyle = "green"; context.fill(); </script> </body> </html>
텍스트예제 <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; </style> </head> <body> <canvas id="mycanvas" width="300" height="200"></canvas> <script> var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); context.font = 'italic 38pt Arial' context.filltext('hello World!', 20, 100); </script> </body> </html>
그라디언트 createlineargradient(x, y, x1, y1) - 선형그라디언트를생성한다. createradialgradient(x, y, r, x1, y1, r1) - 원형그라디언트를생성한다.
선형그라디언트예제 <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; </style> </head> <body> <canvas id="mycanvas" width="300" height="200"></canvas> <script> var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); var gradient = context.createlineargradient(0, 0, 200, 0); gradient.addcolorstop(0, "white"); gradient.addcolorstop(1, "red"); context.fillstyle = gradient; context.fillrect(10, 10, 180, 90); </script> </body> </html>
패턴채우기 <!DOCTYPE HTML> <html> <head>.. </head> <body> <canvas id="mycanvas" width="300" height="200"></canvas> <script> var canvas = document.getelementbyid("mycanvas"); var context = canvas.getcontext("2d"); var image = new Image(); image.src = "pattern.png"; image.onload = function () { var pattern = context.createpattern(image, "repeat"); context.rect(0, 0, canvas.width, canvas.height); context.fillstyle = pattern; context.fill(); ; </script> </body> </html>
이미지그리기 <body> <canvas id="mycanvas" width="600" height="400"></canvas> <script> var canvas = document.getelementbyid("mycanvas"); var context = canvas.getcontext("2d"); var image = new Image(); image.src = "html5_logo.png"; </script> </body> image.onload = function () { context.drawimage(image, 0, 0); ;
도형변환 평행이동 (translation) 신축 (scaling) 회전 (rotation) 밀림 (shear) 반사 (mirror) 행렬을이용한일반적인변환
평행이동 <body> <canvas id="mycanvas" width="600" height="400"></canvas> <script> var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); context.fillstyle = "blue"; context.fillrect(0, 0, 100, 100); context.translate(50, 50); context.fillstyle = "red"; context.fillrect(0, 0, 100, 100); </script> </body>
애니메이션 Bouncing Ball 예제
<!DOCTYPE html> <html> <head> <title>bouncing Ball Example</title> <style> canvas { background: yellow; border: 1px dotted black; </style> Bouncing Ball 예제
Bouncing Ball 예제 <script> var context; var dx = 5; var dy = 5; var y = 100; var x = 100; function draw() { var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); context.clearrect(0, 0, 300, 200); context.beginpath(); context.fillstyle = "red"; context.arc(x, y, 20, 0, Math.PI * 2, true); context.closepath(); context.fill(); if (x < (0 + 20) x > (300-20)) dx = -dx; if (y < (0 + 20) y > (200-20)) dy = -dy; x += dx; y += dy; setinterval(draw, 10); </script> </head>
Bouncing Ball 예제 <body> <canvas id="mycanvas" width="300" height="200"></canvas> </body> </html> 웹브라우저로보기
간단한게임제작 앵그리버드와유사한다음과같은게임을제작
간단한게임만들기 <html> <head> <title>javascript Game</title> <style> canvas { border: 1px dotted red; /* 캔버스에경계선을그려준다. */ background-color: #fcff00; /* 캔버스의배경색을지정한다. */ </style> <script> var context; /* 컨텍스트객체 */ var velocity; /* 사용자가입력한공의초기속도 */ var angle; /* 사용자가입력한공의초기각도 */ var ballv; /* 공의현재속도 */ var ballvx; /* 공의현재 x 방향속도 */ var ballvy; /* 공의현재 y 방향속도 */ var ballx = 10; /* 공의현재 x 방향위치 */ var bally = 250; /* 공의현재 y 방향위치 */ var ballradius = 10; /* 공의반지름 */ var score = 0; /* 점수 */
간단한게임만들기 var image = new Image(); /* 이미지객체생성 */ image.src = "lawn.png"; /* 이미지파일이름설정 */ var backimage = new Image(); backimage.src = "net.png"; var timer; /* 타이머객체변수 */ /* 공을화면에그린다. */ function drawball() { context.beginpath(); context.arc(ballx, bally, ballradius, 0, 2.0 * Math.PI, true); context.fillstyle = "red"; context.fill(); /* 배경을화면에그린다. */ function drawbackground() { context.drawimage(image, 0, 270); context.drawimage(backimage, 450, 60); /* 전체화면을그리는함수 */ function draw() { context.clearrect(0, 0, 500, 300); /* 화면을지운다. */ drawball(); drawbackground();
간단한게임만들기 /* 초기화를담당하는함수 */ function init() { ballx = 10; bally = 250; ballradius = 10; context = document.getelementbyid('canvas').getcontext('2d'); draw(); /* 사용자가발사버튼을누르면호출된다. */ function start() { init(); velocity = Number(document.getElementById("velocity").value); angle = Number(document.getElementById("angle").value); var angler = angle * Math.PI / 180; ballvx = velocity * Math.cos(angleR); ballvy = -velocity * Math.sin(angleR); draw(); timer = setinterval(calculate, 100); return false;
간단한게임만들기 /* 공의현재속도와위치를업데이트한다. */ function calculate() { ballvy = ballvy + 1.98; ballx = ballx + ballvx; bally = bally + ballvy; /* 공이목표물에맞았으면 */ if ((ballx >= 450) && (ballx <= 480) && (bally >= 60) && (bally <= 210)) { score++; document.getelementbyid("score").innerhtml = " 점수 =" + score; clearinterval(timer); /* 공이경계를벗어났으면 */ if (bally >= 300 bally < 0) { clearinterval(timer); draw(); </script> </head>
간단한게임만들기 <body onload="init();"> <canvas id="canvas" width="500" height="300"></canvas> <div id="control"> 속도 <input id="velocity" value="30" type="number" min="0" max="100" step="1" /> 각도 <input id="angle" value="45" type="number" min="0" max="90" step="1" /> <div id="score"> 점수 = 0</div> <button onclick="start()"> 발사 </button> </div> </body> </html> 웹브라우저로보기