Chrome Dinosaur Game (1)
https://www.youtube.com/watch?v=qkTtmgCjHhM
HA2๊ฐ ๋๋๊ณ Solo Day๊ฐ ์ดํ ์์ด์ ์ด์ ์ ํ์ด๋ถ๋ค๊ณผ ํจ๊ป ๊ฒ์์ ๊ตฌํํด๋ณด์์ต๋๋ค.
์ฝ๋์คํ ์ด์ธ ์์ ๋ค๋ฃจ์ง ์๋ ๋ถ๋ถ์ ์ ํด๋ณผ ์ ์๋ค๋ ์ ์์ ์ข์ ๊ธฐํ์๋ ๊ฒ ๊ฐ์ต๋๋ค!
๋ํ HTML, CSS, JS ๋ง์ผ๋ก ๊ฐ๋จํ๊ฒ๋ผ๋ ์ด๋ฐ ๊ฒ์์ ๋ง๋ค ์ ์๋ค๋ ๊ฒ ์ฌ๋ฐ๋ค์ใ ใ
์ด๋ฒ ๊ธ์์๋ ์ค๋ ๊ฒ์์ ์ ๋ฐ์ ๋ ๊ตฌํํ๋ฉด์ ์๋ก ์๊ฒ๋ ๊ฒ๋ค๊ณผ ํ์ผ๋ก ์จ๋จน์ผ๋ฉด ์ข์ ๊ฒ ๊ฐ์ ๊ฒ๋ค์ ์ ๋ฆฌํด๋ณด๋ ค๊ณ ํฉ๋๋ค.
<canvas>
ํ๊ทธ
<canvas>
ํ๊ทธ๋ ์ฒ์ ๋ณธ ํ๊ทธ์์ต๋๋ค. ์นํ์ด์ง ์์์ ๊ทธ๋ฆผ์ ๊ทธ๋ฆด ๋ ์์ฃผ ์ฌ์ฉ๋๋ ํ๊ทธ์
๋๋ค. ์, ๋ฐ์ค, ์ด๋ฏธ์ง ๋ฑ์ ์์๋ฅผ ์ถ๊ฐํ๊ณ ๊ทธ๋ํฝ ์์๋ฅผ ์ฌ์ฉํ๊ณ ์ถ์ ๋ ์ฌ์ฉ๋๋ค๊ณ ํ๋ค์!
HTML์์์ <canvas>
ํ๊ทธ๋ฅผ JS์์ ์ฌ์ฉํ๊ธฐ ์ํด์๋ ์๋์ ๊ฐ์ด ๊ธฐ๋ณธ์ ์ธ ์ธํ
์ด ํ์ํฉ๋๋ค. ์ฝ๋๋ฅผ ์ธ๋ถ์ ์ผ๋ก ๋ ์ดํด๋ณด๋๋กํ๊ฒ ์ต๋๋ค.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth-100;
canvas.height = window.innerHeight-100;
HTMLCanvasElement.getContext( )
getContext
์ ์ธ์๋ contextType, contextAttributes๋ฅผ ๋ฐ์ต๋๋ค.
์ฝ๋ ์์์๋ getContext("2d")
๋ก ๋์ด์๋๋ฐ, 2์ฐจ์ ์์์ ๊ฐ์ฒด๋ฅผ ๋ํํ๋ CanvasRenderingContext2D๋ฅผ ๋ง๋ค์ด์ฃผ๋ ์ญํ ์ ํ๋ ๊ฒ์
๋๋ค.
์ด๋ ๊ฒ ๋ง๋ค๊ณ ๋๋ฉด ๋ค์ํ Method๋ฅผ ์ฌ์ฉํด์ ์ฌ๋ฌ ๋ชจํ์ ๋ง๋ค ์ ์์ต๋๋ค.
fillRect
, moveTo
, clearRect
๋ฑ์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
๋ ์์ธํ ์ค๋ช ์ ์๋ MDN์ ์ฐธ๊ณ ํ์๋ฉด ๋ ๊ฒ ๊ฐ์ต๋๋ค.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
CanvasRenderingContext2D - Web APIs | MDN
The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a
developer.mozilla.org
Global Object
global object๋ global scope์์ ํญ์ ์กด์ฌํ๋ ๊ฐ์ฒด์ ๋๋ค. ๋ธ๋ผ์ฐ์ ์์์ global object๋ window๋ผ๊ณ ํฉ๋๋ค.
ํฌ๋กฌ ๊ฒ์ ์์์์๋ window ๊ฐ์ฒด๋ฅผ ๊ฐ์ง๊ณ canvas์ ๋ฒ์๋ฅผ ์ ํด์ฃผ์์ต๋๋ค.
window.innerWidth / window.innerHeight
์ ๊ทธ๋ฆผ๊ณผ ๊ฐ์ด window.innerHeight๋ ํญ, ๋ถ๋งํฌ๋ฐ ๋ฑ์ ์์๋ฅผ ๋ถํฌํจํ ๋ถ๋ถ์ ์ผ์ปซ์ต๋๋ค. inner๋ผ๋ ๋จ์ด๊ฐ ์๊ธธ๋ outerHeight๋ ์๋ ๊ถ๊ธํด์ ์ฐพ์๋ดค๋๋ฐ outerHeight๋ ํญ, ๋ถ๋งํฌ๋ฐ๊น์ง ํฌํจํ ์ ์ฒด ๋ธ๋ผ์ฐ์ ํฌ๊ธฐ์ ๋์ด๋ฅผ ๋งํ๋ ๊ฒ์ด์์ต๋๋ค. ์ฝ๋๋ฅผ ๋ณด๋ฉด canvas์ ํฌ๊ธฐ๋ฅผ innerHeight์ innerWidth๋ฅผ ํตํด ์ง์ ํด์ค ๊ฒ์ ๋๋ค.
Dinosaur์ Cactus ๋ง๋ค๊ธฐ
Dinosaur์ Cactus์ ๊ฐ์ ์์๋ค์ ์ฌ๋ฌ ์์ฑ์ ์ง๋๊ณ ์๊ธฐ ๋๋ฌธ์ ๊ฐ์ฒด๋ฅผ ๋ฐ๋ก ์ ์ธํด์ค ํ์ ์ฌ์ฉํ๋ ๊ฒ์ด ์์ฑ ๊ด๋ฆฌ์ ๋์ฑ ๊ฐํธํฉ๋๋ค.
๋ํ ๊ฐ๊ฐ์ ๊ฐ์ฒด์ ๋ฉ์๋๋ค๋ ๊ด๋ฆฌํด์ฃผ๊ธฐ ํธ๋ฆฌํด์ง๋๋ค.
๋์ค์ ๊ฒ์ ํ๋ก์ ํธ๋ฅผ ์ ๋๋ก ์งํํ ๋ ๋๋ฌด ํฐ ๊ท๋ชจ๊ฐ ์๋๋ผ๋ฉด ๊ฐ๋จํ๊ฒ ๊ฐ์ฒด๋ก ๊ด๋ฆฌํด์ฃผ๊ธฐ ์ข๊ฒ ๋ค๊ณ ์๊ฐํ์ต๋๋ค.
์ด ์์์์๋ dino๋ผ๋ ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ , cactus๋ผ๋ ํด๋์ค๋ฅผ ๋ง๋ค์ด์ฃผ์์ต๋๋ค.
Cactus์ ๊ฒฝ์ฐ, ์ฌ๋ฌ ์ ์ธ์ฅ๋ค์ด ์ง์์ ์ผ๋ก ๋์์ผ ํ๊ธฐ ๋๋ฌธ์ ํด๋์ค๋ฅผ ์ ์ธํ๊ณ ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ ๋ฐฉ์์ผ๋ก ์งํ๋ฉ๋๋ค.
class Cactus {
constructor() {
this.x = 800;
this.y = 200;
this.width = 50;
this.height = 50;
}
draw() {
ctx.fillStyle = 'pink';
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}