
<canvas>는 HTML 요소 중 하나로서, 스크립트(보통은 자바스크립트)를 사용하여 그림을 그리는 데에 사용된다. 예를 들면, 그래프를 그리거나 사진을 합성하거나, 간단한 애니메이션을 만드는 데에 사용될 수 있다.
canvas는 Apple의 Webkit에 처음 도입되어 Mac OS X 대시보드에 사용되었고, 이후 다른 브라우저에도 구현되어 왔으며 현재 대부분의 주요 브라우저에서 지원된다.
<canvas id="tutorial" width="150" height="150"></canvas>
마치 img 태그처럼 보이지만 요소에는 width와 height 2가지 요소만 있다!
이 요소는 모두 선택사항이고 DOM 프로퍼티를 사용하여 설정할 수 있다.
기본값은 width = "300" height = "150"
이 요소의 값을 css에 의해 임의로 크기를 정할 수 있지만 이미지는 레이아웃의 크기에 맞게 조정되므로 css 크기 지정이 초기 캔버스의 비율을 고려하지 않으면 왜곡된다.
만약, 왜곡된 것처럼 보이는 경우 css를 사용하지 않고 canvas태그에서 크기를 지정한다.
익스플로어9 이하와 같이 canvas를 지원하지 않은 브라우저에서는 대체 콘텐츠를 제공해야 되는데 canvas 태그 안에 그 대체 콘텐츠를 작성하면 미지원 브라우저에서는 canvas태그를 무시하고 태그 안의 대체 콘텐츠를 실행한다.
<canvas id="clock" width="150" height="150">
<img src="images/clock.png" width="150" height="150" alt=""/>
</canvas>
대체 컨텐츠가 제공되는 방식때문에 img 요소와 일부 태그들과 달리 canvas는 태그를 닫기 태그(</canvas>)가 필수이다.
//DOM 요소로 canvas를 가져오고
var canvas = document.getElementById('tutorial');
//getContext로 드로잉 컨텍스트에 접근한다.
var ctx = canvas.getContext('2d');
브라우저에서 canvas 지원을 확인하고 싶다면 조건문으로 간단히 확인 할 수 있다.
getContext를 가져올 수 있다면 true로 return 할 것이다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>브라우저 지원여부 검사</title>
</head>
<body>
<h1>브라우저 지원여부 검사</h1>
<h2>콘솔창을 확인하세요</h2>
<canvas id="tutorial"></canvas>
</body>
<script>
var canvas = document.getElementById('tutorial');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
console.log("canvas를 지원합니다.")
} else {
// 오류를 리턴해도 된다.
console.log("canvas를 지원하지 않습니다.")
}
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>기본예제</title>
</head>
<body>
<h1>기본예제</h1>
<canvas id="canvas" width="150" height="150"></canvas>
</body>
<script>
//canvas 태그 안에서의 x,y축이 된다!
function draw(){
let canvas = document.getElementById('canvas');
//여기서 canvas를 지원하면 실행되도록 한다.
if(canvas.getContext){
let ctx = canvas.getContext('2d');
//붓을 해당 색깔에 뭍힌다.
ctx.fillStyle = "rgb(200,0,0)";
//x,y,너비,높이
ctx.fillRect(10,10,50,50)
//붓을 해당 색깔에 뭍힌다.
ctx.fillStyle = "rgba(0,0,200,0.5)";
ctx.fillRect(30,30,50,50);
}
}
draw();
</script>
</html>