캔버스는 <canvas>
요소로 생성
캔버스는 HTML 페이지 상에서 사각형태의 영역
실제 그림은 자바스크립트를 통하여 코드로 그려야 한다.
<canvas id="myCanvas" width="300" height="100"></canvas>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
canvas1.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!-- 캔버스 요소를 정의한다. -->
<canvas id="myCanvas" width="200" height="100"
style="border: 1px dotted red"></canvas>
<script>
// 먼저 캔버스 요소를 찾는다.
var canvas = document.getElementById("myCanvas");
// 캔버스에서 컨텍스트를 얻는다.
var context = canvas.getContext("2d");
context.fillStyle = "#00FF00";
// 캔버스 위에 사각형을 그린다.
context.fillRect(0, 0, 100, 50);
</script>
</body>
</html>
canvas_line.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// 경로를 초기화 한다.
context.beginPath();
context.moveTo(0, 0);
context.lineTo(100, 100);
context.lineTo(150, 50);
context.lineTo(200, 100);
context.stroke();
</script>
</body>
</html>
canvas_rect.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(10, 10, 100, 100);
context.rect(50, 50, 100, 100);
context.stroke();
</script>
</body>
</html>
채워진 사각형을 그리고 싶으면 stroke() 대신에 fill()을 호출하면 된다.
canvas_rect1.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(10, 10, 100, 100);
// 채우기 속성을 노란색으로 지정한다.
context.fillStyle="yellow";
context.fill();
context.rect(50, 50, 100, 100);
context.stroke();
</script>
</body>
</html>
캔버스에 원을 그리기 위해서는 arc() 메서드를 사용한다.
arc(x, y, radius, startAngle, endAngle, anticlockwise)
(x, y)를 중심으로 반지름이 radius인 원을 그린다.
start는 시작각도, end는 종료각도이다.
canvas_arc.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.arc(100, 100, 80, 0, 2.0*Math.PI, false);
context.strokeStyle = "red";
context.stroke();
context.beginPath();
context.arc(100, 100, 60, 0, 1.5*Math.PI, false);
context.closePath();
context.strokeStyle = "blue";
context.stroke();
context.beginPath();
context.arc(100, 100, 40, 0, 1.5*Math.PI, false);
context.strokeStyle = "green";
context.stroke();
</script>
</body>
</html>
베지어 곡선 같은 3차 곡선도 그릴 수 있다. 베지어 곡선은 4개의 제어점 안에 그려지는 3차 곡선이다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(90, 130);
context.bezierCurveTo(140, 10, 288, 10, 288, 130);
context.lineWidth = 10;
context.strokeStyle = 'black';
context.stroke();
</script>
</body>
</html>
일반적인 도형은 경로(path)를 형성해서 그리면 된다.
경로는 beginPath() 호출로 시작해서 closePath() 호출로 종료한다.
canvas_path.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(50, 100);
context.lineTo(75, 50);
context.lineTo(100, 100);
context.closePath();
context.fillStyle = "green";
context.fill();
</script>
</body>
</html>
캔버스에 텍스트를 그리기 위해서는 다음과 같은 속성의 메서드를 사용한다.
font: 텍스트를 그리는데 사용되는 폰트 속성을 정의한다.
fillText(text, x, y): 캔버스에 채워진 텍스트를 그린다.
strokeText(text, x, y): 캔버스에 텍스트의 외곽선만을 그린다.
canvas_text.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.font = 'italic 38pt Arial';
context.fillText('Hello World', 20, 100);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.font = 'italic 38pt Arial';
context.strokeText('Hello World!', 20, 100);
</script>
</body>
</html>
canvas_line_prop.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
ctx.beginPath();
ctx.lineWidth = 20;
ctx.lineCap = "round";
ctx.moveTo(20, 20);
ctx.lineTo(200, 20);
ctx.stroke();
</script>
</body>
</html>
createLinearGrandient(x, y, x1, y1)
: 선형 그라디언트를 생성한다.createRadialGrandient(x, y, r, x1, y1, r1)
: 원형 그리디언트를 생성한다.<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var gradient = context.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "white");
gradient.addColorStop(1, "red");
context.fillStyle = gradient;
context.fillRect(10, 10, 180, 90);
</script>
</body>
</html>
canvas_gra1.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var gradient = context.createRadialGradient(70, 50, 10, 80, 60, 120);
gradient.addColorStop(0, "white");
gradient.addColorStop(1, "red");
context.fillStyle = gradient;
context.fillRect(10, 10, 180, 90);
</script>
</body>
</html>
createPattern()
메서드를 이용한다.
canvas_pattern.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var image = new Image();
image.src = "pattern.png";
image.onload = function() {
var pattern = context.createPattern(image, "repeat");
context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle = pattern;
context.fill();
}
</script>
</body>
</html>
drawImage()
메서드를 이용한다.
canvas_image.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var image = new Image();
image.src = "html5_logo.png";
image.onload = function() {
context.drawImage(image, 0, 0);
};
</script>
</body>
</html>
HTML5에서는 2차원 변환인 평행이동(translation), 신축(scaling), 회전(rotation)을 비롯한 모든 변환을 지원한다.
canvas_trans.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="600" height="400"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.fillStyle = "blue";
context.fillRect(0, 0, 100, 100);
// 좌표계를 평행 이동 시킨다.
context.translate(50, 50);
context.fillStyle = "red";
context.fillRect(0, 0, 100, 100);
</script>
</body>
</html>
context.clearRect(0, 0, 300, 200);
context.beginPath();
context.fillStyle = "red";
context.arc(x, y, 20, 0, Math.PI*2, true);
context.closePath();
context.fill();
x += dx;
y += dy;
반사되는 코드
if (x < (0 + 20) || x > (300 - 20))
dx = -dx;
if (y < (0 + 20) || y > (200 - 20))
dy = -dy;
x += dx;
y += dy;
setTimeout(doSomething, 500); // 500밀리초 후에 doSomething()을 호출한다.
setInterval(doSomething, 500); // 매 500밀리초마다 doSomething()을 호출한다.
canvas_ball.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Bouncing Ball Example</title>
<style>
canvas {
background: yellow;
border: 1px dotted black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="200"></canvas>
<script>
var context;
var dx = 5; // 볼이 한 번에 움직이는 거리
var dy = 5;
var y = 100;
var x = 100;
function draw() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.clearRect(0, 0, 300, 200);
context.beginPath();
context.fillStyle = "red";
context.arc(x, y, 20, 0, Math.PI*2, true); // 공을 그린다.
context.closePath();
context.fill();
if (x < (0 + 20) || x > (300 - 20)) // 공이 벽에 닿음 반사시킨다.
dx = -dx;
if (y < (0 + 20) || y > (200 - 20))
dy = -dy;
x += dx;
y += dy;
}
setInterval(draw, 10); // 10 밀리초마다 draw()를 호출한다.
</script>
</body>
</html>