Javascript에서 canvas라는 것을 이용하면 그림을 그려볼 수 가 있다. 이를 활용해서 게임 같은것도 만들수 있을 것 같다.
canvas tag를 이용해서 body에 정의를 해놓고
<body onload="onload()">
<canvas id="canvas" style="background-color:rgb(185, 185, 185)" width="800" height="400"></canvas>
</body>
javascript 코드 제어가 가능하다. context 객체를 가져와서 거기에 그려주면 된다.
let canvas = document.getElementById('canvas');
let context = gCanvas.getContext("2d");
const { width, height } = canvas;
beginPath로 시작을 하고, arc, line, rect 등을 호출하면 원, 라인, 네모 등의 영역을 그린 후
fill을 불러서 채우거나, stroke를 호출해서 선을 그리게 한다.
let x1 = 100, y1 = 100, x2 = 200, y2 = 200;
let x = 300, y = 300, size = 50;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = 'white';
context.strokeStyle = "blue";
context.beginPath();
context.arc(x, y, size, 0, 2 * Math.PI);
context.fill();
context.stroke();
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();

fillRect 나 strokeRect 로 한번에 할 수 있는 함수도 있다.
더 많은 그리기 함수는 아래를 참고
CanvasRenderingContext2D: strokeRect() method - Web APIs | MDN (mozilla.org)
CanvasRenderingContext2D: strokeRect() method - Web APIs | MDN
The CanvasRenderingContext2D.strokeRect() method of the Canvas 2D API draws a rectangle that is stroked (outlined) according to the current strokeStyle and other context settings.
developer.mozilla.org
반복해서 그림을 업데이트를 할 필요가 있을 경우,
window.requestAnimationFrame(draw);
를 사용하면 된다. draw는 context로 그림을 그리는 함수로 유저가 작성해야된다.
이 함수를 이용하면, 그림 그리기가 준비가 되었을 때 화면업데이트를 해주게 되며, (아마도 draw함수가 다 수행되었을 때일 듯 싶다) 1초에 60번까지 업데이트하며, 필요에 따라 조절이 된다고 한다.
setInterval 이나 setTimeout으로 직접 반복 업데이트를 해도 된다고 한다.
여기에 더 재밌는 예시들이 있다.
Basic animations - Web APIs | MDN (mozilla.org)
Basic animations - Web APIs | MDN
Since we're using JavaScript to control <canvas> elements, it's also very easy to make (interactive) animations. In this chapter we will take a look at how to do some basic animations.
developer.mozilla.org
캔버스를 이용해서 간단한 게임을 한번 만들어 볼까 한다.
'SW 개발 참고 > Javascript' 카테고리의 다른 글
Javascript canvas로 슈팅 게임 만들기 (0) | 2023.11.19 |
---|---|
나만의 비트코인 차트 만들기 (HTML, JS) (0) | 2023.11.19 |
Bootstrap을 이용하여 손쉽게 예쁜 UI 구성 (0) | 2023.11.19 |
window.localStorage 사용으로 이전 선택 저장하기 (0) | 2023.11.19 |
브라우저 Javascript Candle Chart 그리기 (0) | 2023.11.19 |