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();

 

 

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

 

캔버스를 이용해서 간단한 게임을 한번 만들어 볼까 한다.

 

 

+ Recent posts