본문 바로가기
개발 공부/canvas

Canvas을 사용하여 벽돌깨기 게임 만들기1 (캔버스 생성과 그리기)

by 억만장작 2021. 7. 17.

순수 자바스크립트를 이용하여 2D 벽돌깨기 게임을 만들자.

주의! 이 글은 MDN의 Tutorial인 순수한 자바스크립트를 이용한 2D 벽돌깨기 게임을 보고 공부한 것이다. 좀 더 정확한 내용을 원한다면 링크를 따라가자. 그리고 내 코드와 MDN의 코드가 다를 수 있지만 이론은 같으니 문제되는 부분이 있다면 수정해야지 ㅎㅎ

1. 캔버스 생성과 그리기

먼저 html파일을 만들고 canvas element를 만들어야한다.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>mijeong Game</title>
	<link rel="stylesheet" href="./style.css">
</head>
<body>
	<canvas id="canvas"></canvas>
	<script src="./canvas.js"></script>
</body>
</html>

id가 canvas인 canvas element를 만들고 canvas.js파일과 style.css파일을 만들어 줬다.

 

기본적인 style을 맞춰주자. 

* {
	padding: 0;
	margin: 0;
}

canvas {
	background: #eee;
	display: block;
	margin: 0 auto;
}

 

먼저 cavas를 javascript에서 참조할 수 있게 가져온다. 나는 document.querySelector를 사용하여 가져올 것이다. 그리고 캔버스에 실질적으로 사용되는 도구인 2D rendering context를 ctx라는 변수에 넣어둘 것이다.

const canvas = document.querySelector("#canvas")
const ctx = canvas.getContext("2d")

그리고 아래의 코드를 추가해보자.

ctx.beginPath()
ctx.rect(10, 10, 50, 50)
ctx.fillStyle = "green"
ctx.fill()
ctx.closePath()

정확히는 모르겠지만 beginPath와 closePath사이에 내가 그리고자 하는 코드가 들어간다. rect()는 사각형을 그리는 함수이다. 인자는 순서대로 x, y 위치 그리고 width, height를 넣어준다. 단위는 픽셀이다. fillStyle을 통해 색을 넣어주고 fill()을 해주면 그제서야 그려지는 형태이다.

 

원또한 그릴 수 있다.

ctx.beginPath()
ctx.arc(75, 75, 25, 0, Math.PI * 2, false)
ctx.fillStyle = "red"
ctx.fill()
ctx.closePath()

arc()는 원을 그리는 함수이다. 인자는 순서대로 x, y위치 그리고 반지름, 시작각, 끝 각, 그리기 시작할 방향 이다. 시작각, 그릴 각, 시작할 방향이 이해가 잘 가지 않을 것이다. 시작각은 원을 그릴 때 시작하는 각을 말한다. 그릴 각은 360도를 다 그릴지 90도만 그릴지 그릴 각도를 정하는 것이다. 시작할 방향에서 default와 true는 반 시계 방향, false는 시계방향으로 그리기 시작한다. 

 

stroke()를 사용하여 외곽선만 그릴 수도 있다.

ctx.beginPath()
ctx.rect(40, 40, 70, 70)
ctx.strokeStyle = "rgba(0, 0, 255, 0.5)"
ctx.stroke()
ctx.closePath()

fillStyle과 fill() 대신 strokeStyle과 stroke()를 사용한다. 여기서 rgba는 rgb와 투명도로 색을 넣어주는 함수형 표기법이다.

 

최종적으로는 아래와 같이 출력될 것이다.

최종 코드

const canvas = document.querySelector("#canvas")
const ctx = canvas.getContext("2d")

ctx.beginPath()
ctx.rect(50, 50, 50, 50)
ctx.fillStyle = "green"
ctx.fill()
ctx.closePath()

ctx.beginPath()
ctx.arc(75, 75, 25, 0, Math.PI * 2, false)
ctx.fillStyle = "red"
ctx.fill()
ctx.closePath()

ctx.beginPath()
ctx.rect(40, 40, 70, 70)
ctx.strokeStyle = "rgba(0, 0, 255, 0.5)"
ctx.stroke()
ctx.closePath()

 

댓글