2011. 9. 5. 12:30

사각형(Rectangle)을 캔버스에 그리는 것을 통해서 어떻게 원하는 도형을 작성하고 다루게 되는지를 설명해 드릴려고 합니다.

<canvas id="c1" width="200" height="200" style="border:solid 1px #000000;"> </canvas>
<button onclick="draw_square();return true;">Red Square</button>
<script>
   function draw_square() {
      var c1 = document.getElementById("c1");
      var c1_context = c1.getContext("2d");
      c1_context.fillStyle = "#f00";
      c1_context.fillRect(50, 50, 100, 100);
   }
</script>

위와 같이 캔버스를 하나 정의하고 버튼을 정의했습니다. 버튼의 OnClick 이벤트는 Java Script의 draw_square()를 호출하게 되어 있습니다. 버튼을 누르면 아래와 같은 실행 결과를 얻을 수 있습니다.

소스코드를 보면 누구나 이해할 수 있을 만큼 간단한 소스로 먼저 Java Script에서 캔버스를 얻어내는 부분입니다.
 
var c1 = document.getElementById("c1");

캔버스를 찾아내서 c1이라는 변수에 일단 저장한 다음 c1이라는 이름의 캔버스에서 2D 컨텍스트를 가져와서 c1_context로 정의합니다.

var c1_context = c1.getContext("2d");

c1_context의 내용을 빨간 색으로 채우기 위해서 fillStyle 속성을 '#f00'로 채우고 있습니다.

c1_context.fillStyle = "#f00";

마지막으로 사각형을 직접 채웁니다.

c1_context.fillRect(50, 50, 100, 100);

코드를 보시면 아시겟지만. 캔버스의 역할은 200 X 200짜리 그림판을 제공해 줄 뿐이고 실제 액션은 모두 Java Script로 이루어지고 있는 있을 것을 볼 수 있습니다. 즉 HMTL5을 잘 다루기 위한 필 수 조건은 바로 Java Script라고 보시면 될 것 같습니다.
아래에 있는 표는 관련된 메서드와 속성입니다.

Methods of "Context" Descriptions
fillStyle CSS Color, pattern or gradient within the shape. Default fillStyle is solid black color.
strokeStyle Color or CSS style of the lines of the shape
fillRect(x, y, width, height) Draw a rectangle start from coordinate x and y and size of width x height.
strokeRect(x, y, width, height) Draw a rectangle with just its edges.
clearRect(x, y, width, height) Clear the area specified in x, y coordinate and area of width x height
 

메소드나 속성의 이름을 보면 대충 뭘하는지 다들 짐작 할 수 있을 것 같습니다.
아래의 소스는 한 번쯤 실행시켜 보면 감을 잡는데 더 도움이 될 것 같습니다.

<div ><canvas id="Canvas2" width="200" height = "200" style="border:solid 1px #000000;"></canvas>
<div>
   <button onclick="blue_square_2();return true;">Blue Square</button>
   <button onclick="red_stroke_2();return true;">Red Square</button>
   <button onclick="clear_rect_2();return true;">Erase Everything</button>
</div>
</div>
<script>
   var c2 = document.getElementById("c2");
   var c2_context = c2.getContext("2d");
   function blue_square_2() { //Blue color square
      c2_context.fillStyle = "#00f";
      c2_context.fillRect(50, 50, 100, 100);
   }

   function red_stroke_2() { //Red color edges
      c2_context.strokeStyle = "#f00";
      c2_context.strokeRect(45, 45, 110, 110);
   }

   function clear_rect_2() { //Clear all
      c2_context.clearRect(40, 40, 120, 120);
   }
</script>

김영욱 iwinkey@hotmail.com

현재 한국마이크로소프트에서 Evangelist로 근무하고 있으며 국내 유수의 대기업 프로젝트에 참여했던 경험과 Microsoft MVP로 다년간 활동했습니다.
올해는 컨슈머와 관련된 앱을 만드는 다양한 업체들을 발굴하고 지원하는 일을 맡고 있습니다.


HTML5 강좌 전체 목록
  1. HTML5 DocType의 정의
  2. HTML5 Header stuff
  3. Audio
  4. Video
  5. Canvas
    Canvas: Rectangle
    Canvas: Shadow
    Canvas: Path
    Canvas: Image
    Canvas: Text
  6. Web form 2.0
    Input Attr: Placeholder
    Input Attr: Autofocus
    Input Attr: Required field
    Input Attr: DataList
    Input Type: Search
    Input Type: Email, URL, Phone
    Input Type: Range
    Input Type: Number
    Input Type: Date
    Input Type: Color
  7. Towards Semantic Web
    Semantic <mark>
    Semantic <time>
    Semantic <meter>
    Semantic <progress>
    Semantic <section>
    Semantic <header>
    Semantic <footer>
    Semantic <nav>
    Semantic <article>
    Semantic <aside>
  • 양현우 2011.11.03 11:03

    아래소스에서 canvas의 id가 다르네요. 별거 아니지만...
    아무튼 많은 도움이 되는 군요. 감사합니다.

  • 나그네 2012.03.05 14:09

    별거 아니라기 보다 작동이 안되겠죠 ^^;;
    canvas id="c2" 로 지정해줘야 작동이 됩니다.

2011. 9. 5. 09:40

5. HTML5 Canvas

HTML5 2011. 9. 5. 09:40

HTML5의 인기있는 주제중의 하나가 캔버스(Canvas) 입니다. HTML5의 캔버스는 미술에서 그림을 그릴 때 사용하는 캔버스처럼 어떤한 것이라도 올려 놓고 그리는 용도로 사용할 수 잇습니다.  

 캔버스는 기본적으로 어떠한 것도 제공되지 있는 비여있는 공간을 제공해 줍니다. 비여있는 공간에 Java Script를 이용해서 연필이나 페인트 블러쉬를 사용해서 원하는 것을 표현할 수 있습니다. 
 
 물론 캔버스가 단순히 이미지를 표현하는 툴은 아닙니다. 오히려 그 이상의 역할을 할 수 있습니다. 이미지나 비디오 그리고 간단한 애니메이션에 이르기까지 많은 역할을 캔버스 하나로 커버할 수 있습니다.

캔버스를 정의하는 것은 아주 간단합니다.

<canvas width="200" height="200"></canvas>

위의 같이 한 줄을 입력하면 넓이와 높이가 200인 빈 공간이 하나 생깁니다. 사실 캔버스가 제공하는 기능은 바로 이 빈공간이라고 할 수 있습니다.
 이 빈공간에서 Java Script로 다양한 그림을 그리거나 객체를 표현 할 수 있습니다.

<canvas id="Canvas1" width="200" height="200" style="border:solid 1px #000000"></canvas>

위의 예제는 캔버스에 가볍게 스타일을 지정해 본 경우 입니다. 
현재 캔버스를 지원하는 브라우저와 버전입니다.  

Browsers Basic Canvas Support
IE 7 ✓ (requires ExplorerCanvas)
IE 9 Beta
Firefox 3.0
Safari 3.0
Chrome 3.0
Opera 10


김영욱 iwinkey@hotmail.com

현재 한국마이크로소프트에서 Evangelist로 근무하고 있으며 국내 유수의 대기업 프로젝트에 참여했던 경험과 Microsoft MVP로 다년간 활동했습니다.
올해는 컨슈머와 관련된 앱을 만드는 다양한 업체들을 발굴하고 지원하는 일을 맡고 있습니다.


HTML5 강좌 전체 목록
  1. HTML5 DocType의 정의
  2. HTML5 Header stuff
  3. Audio
  4. Video
  5. Canvas
    Canvas: Rectangle
    Canvas: Shadow
    Canvas: Path
    Canvas: Image
    Canvas: Text
  6. Web form 2.0
    Input Attr: Placeholder
    Input Attr: Autofocus
    Input Attr: Required field
    Input Attr: DataList
    Input Type: Search
    Input Type: Email, URL, Phone
    Input Type: Range
    Input Type: Number
    Input Type: Date
    Input Type: Color
  7. Towards Semantic Web
    Semantic <mark>
    Semantic <time>
    Semantic <meter>
    Semantic <progress>
    Semantic <section>
    Semantic <header>
    Semantic <footer>
    Semantic <nav>
    Semantic <article>
    Semantic <aside>