마크업/Html & Css

[HTML][Canvas] 태그 Canvas 알아보기

Rainbow🌈Coder 2022. 12. 23. 11:45
728x90

 

 

<canvas id="canvas1" height="400" width="400">This browser doesn't support canvas</canvas>

 

그리고 위의 DOM 객체를 가져와서 context를 뽑아낸 다음에 조작해서 써야한다.

 

var canvas = document.getElementById("canvas1");
var context = canvas.getContext("2d");

context를 가지고 여러 가지 도형이나 그림을 그리면 된다.

 

: fillRect로 채워진 사각형, fillText로 텍스트, moveTo로 시작점으로 간다음 lineTo로 이은 선, rect로 속이 빈 사각형을 그려주기

var canvas = document.getElementById("canvas1");
var context = canvas.getContext("2d");
context.fillRect(0, 0, 350, 100);
context.fillText("Hello, CANVAS!", 155, 110);
context.beginPath(); context.moveTo(10, 200);
context.lineTo(200, 200);
context.rect(0, 0, 400, 400);
context.stroke();
context.closePath();

위와 같이 스크립트를 분리해서 작성해도 되고, 아래와 같이 window.onload=function(){} 이용할 수도 있다.

<!DOCTYPE html>
<html lang="ko">
<head>
<script>
	window.onload=function()
	{
		var canvas = document.getElementById("canvas1");
		var context = canvas.getContext("2d");

		context.fillRect(0,0,150,100);
		context.fillText("Hello, HTML5!",155,110);
		context.beginPath();
		context.moveTo(170,200);
		context.lineTo(300,200);

		context.rect(0,0,400,400);

		context.stroke();

		context.closePath();
	};
</script>
</head>
<body>
<canvas id="canvas1" height="400" width="400">This browser doesn't support canvas</canvas>
</body>
</html>

 

 

 

 

참고 링크 : https://unikys.tistory.com/274

 

 

 

 

 

 

 

 

 

 

728x90