1.1 캔버스 요소
캔버스 안에 컨텐츠는 브라우저에서 캔버스 태그를 지원 안할 경우 대체 텍스트를 제공한다.
<!DOCTYPE html>
<html>
<head>
<title>A Simple Canvas Example</title>
<style>
body { background-color: #ddd }
#canvas { margin: 10px; padding: 10px; background-color: #fff; border: thin inset #aaa; }
</style>
</head>
<body>
<canvas id="canvas" width="600" height="300">
Canvas not supported
</canvas>
<script src="example.js"></script>
</body>
</html>
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
context.font = '38pt Arial';
context.fillStyle = 'cornflowerblue';
context.strokeStyle = 'blue';
context.fillText('Hello Canvas', canvas.width / 2 - 150, canvas.height / 2 + 15);
context.strokeText('Hello Canvas', canvas.width / 2 - 150, canvas.height / 2 + 15);
document.getElementById()를 사용해 캔버스에 대한 참조를 가져온다.- 캔버스에서
getContext('2d')를 호출해 그래픽 콘텍스트를 가져온다. (괄호 안의 2d의 d는 반드시 소문자로 적어야한다.) - 가져온 그래픽 콘텍스트를 사용해 캔버스에 그린다.
- 먼저 캔버스의 콘텍스트에 대한 참조를 가져온 후,
- 자바스크립트에서는 콘텍스트의
font,fillStyle,strokeStyle속성을 설정하고 텍스트를 그리고 색으로 채웠다. fillText()메서드는fillStyle의 특성에 따라 텍스트를 칠하며strokeText()메서드에서는strokeStyle을 사용해 텍스트의 특성에 따라 윤곽을 그린다.fillStyle속성과strokeStyle속성은 CSS 색상이나, 그라디언트 또는 패턴이 될 수 있다.fillText()메서드와strokeText()메서드는 텍스트와 이 텍스트를 표시할 수 있도록 캔버스 내 위치(x, y) 등 세 가지 인수가 있다.- 위 예제에선 상수값을 활용해 텍스트를 중앙에 위치시키고 있다. (하지만 중앙정렬시 상수값 활용은 좋은 방법이 아니다.)
픽셀(px)은 캔버스 폭과 높이 설정에 적당하지 않다.
캔버스를 지원하는 브라우저에서 픽셀(px)을 광범위하게 사용하고 있지만,
캔버스 명세서에서는 캔버스width속성과height속성에 픽셀(px) 값을 사용하는 방법을 기술적으로 허락하지 않는다.
또한, 캔버스 명세서를 보면width와height속성값은 음이 아닌 정수로만 사용할 수 있다.
캔버스의 기본 크기는 300 X 150 픽셀이다.
기본적으로 브라우저에서는 너비 300픽셀, 높이 150픽셀인canvas요소를 생성한다.
하지만width속성과height속성을 정의해canvas요소의 크기를 변경할 수 있다.물론 CSS 속성을 이용해
canvas요소의 크기를 변경할 수도 있지만,
CSS 속성을 이용해canvas요소의 너비와 높이를 변경하면 원치 않는 결과가 발생할 수 있다.