사실 canvas 엘리먼트를 가지고 그래픽을 표현 할 수는 없습니다.

자바스크립트의 도움이 꼭 필요합니다.

쉽게 생각해 canvas는 우리가 그림을 그릴수 있도록 도화지를 한장 제공한다고 생각하면됩니다.


사각형을 그리는 메소드는 다음과 같이 3가지를 사용할 수 있다.

fillRect(x, y, width, height);   

clearRect(x, y, width, height);

strokeRect(x, y, width, height);


x와 y는 그려질 사각형의 위치를 지정해주는 속성이다. 그 지점이 좌표(x, y)를 의미합니다.

width와 height는 사각형의 크기를 지정해 줄 수 있습니다.


fillStyle 속성은 color, gradient, pattern 값을 부여해 줄 수 있습니다.


gradient를 주기위해서는 createLinearGradient(x0, y0, x1, y1) 메소드와 

createRadialGradient(x0, y0, r0, x1, y1, r1) 메소드를 사용할 수 있습니다.


pattern을 주기위해서는 createPattern(img, repeat | repeat-x | repeat-y | no-repeat)메소드를 사용합니다.

img에는 자신이 사용할 이미지를 넣어줍니다.


context.fillStyle="#FF0000";

context.fillRect(25,25,100,100); // 속이 꽉찬 사각형

 

context.clearRect(40,40,60,60); // 지정한 영역을 투명하게 만들어준다

 

context.strokeStyle="green";

context.strokeRect(45,45,50,50); // 사각형의 테두리를 그려준다



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>사각형그리기</title>
    <script>
var canvas, context;
window.addEventListener("load", InitEvent, false);
function InitEvent(){
canvas = document.getElementById("square");
context = canvas.getContext("2d");
 
context.fillStyle="#FF0000";
context.fillRect(25,25,100,100); // 속이 꽉찬 사각형
 
context.clearRect(40,40,60,60); // 지정한 영역을 투명하게 만들어준다
 
context.strokeStyle="green";
context.strokeRect(45,45,50,50); // 사각형의 테두리를 그려준다
}
</script>
    <style>
#square{
border: 1px solid black
}
</style>
</head>
<body>
    <canvas id="square" width="150" height="150"></canvas>
</body>
</html>
cs


'프로그래밍 > Html & CSS' 카테고리의 다른 글

[HTML5] canvas  (0) 2015.01.20
html문서의 기본 뼈대  (0) 2014.08.13
overflow  (0) 2014.08.13
네비게이션 메뉴 만들기  (0) 2014.08.13
Margin & Padding  (0) 2014.08.13