2011. 9. 7. 12:30

5.5 HTML5 Canvas: Text

HTML5 2011. 9. 7. 12:30

<div><canvas id="c6" width="600" height = "200" style="border:solid 1px #000000;"></canvas>
<div>
<button onclick="showFillText();return true;">Fill Text</button>
<button onclick="showStrokeText();return true;">Stroke Text</button>
<button onclick="Clear_text();return true;">Erase Everything</button>
</div>
</div>

<script>
  var c6 = document.getElementById("c6");
  var c6_context = c6.getContext("2d");

  function showFillText() {
    c6_context.fillStyle = '#f00';
    c6_context.font = 'italic bold 30px sans-serif';
    c6_context.textBaseline = 'bottom';
    c6_context.fillText('HTML5 is cool!', 50, 100);
  }

  function showStrokeText() {
    c6_context.strokeStyle = "#003300";
    c6_context.font = '40px san-serif';
    c6_context.textBaseline = 'bottom';
    c6_context.strokeText('HTML5 is cool?', 300, 100);
  }

  function Clear_text() {
    c6_context.clearRect(1, 1, 600, 300);
  }
</script>


Method Description
fillText(text,x,y) Print the text with solid color within. Text color is determined by fillStyle().
strokeText(text,x,y) Print the text with only color the outline of the text. Text color is set by strokeStyle().
strokeStyle CSS color for text that call strokeText
fillStyle CSS color for text that call fillText
font CSS font style such as "bold, 10px, san-serif"
textBaseline This is a little bit tricky to explain. We will need another demo. The value for this propery can be "top", "hanging", "middle", "alphabetic", "ideographic" and "bottom". Default value is "alphabetic".

HTML5에서 Canvas에 원하는 텍스트를 출력할 수도 있습니다. 텍스트를 출력하는 것이 텍스트를 하나의 객체 단위로 표현하다기 보다는 일종의 비트맵 이미지로 글자를 그려 넣는다는 표현이 더 맞을 것 같습니다.

글자를 Canvas 위에 표현하기 위해서는 fillStyle, font, textBaseline, fillText등을 사용해서 표현해야 합니다.
fillStyle은 글자 색을 표현하고 font는 폰트를 출력한다. textBaseline의 경우는 텍스트의 기준 위치를 잡을때 사용할 수 있으며 실제 글은 fillText로 지정할 수 있습니다.


Baseline은 앞에서 이야기 한 것과 같이 폰트 위치의 기준선을 설정하는 역할을 합니다.

c7_context.textBaseline = "top";
c7_context.
fillText('Top', 5, 100);

c7_context.textBaseline = "bottom";
c7_context.fillText('Bottom', 80, 100);

c7_context.textBaseline = "middle";
c7_context.fillText('Middle', 200, 100);

c7_context.textBaseline = "alphabetic";
c7_context.fillText('Alphabetic', 300, 100);

c7_context.textBaseline = "hanging";
c7_context.fillText('Hanging', 400, 100);


텍스트를 마지막으로 캔버스의 사용방법을 정리합니다.
캔버스의 활용방법은 훨씬 더 많지만 여기서는 가장 기본적인 기능들을 사전적으로 정리하는 선에서 마치려고 합니다. ^^



김영욱 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>
  • 학생 2014.12.03 15:17

    안녕하세요 온라인상에서 뵈니 더반갑습니다

    도움이 많이 되었습니다. 감사합ㄴ디ㅏ.

2011. 9. 7. 08:30

5.4 HTML5 Canvas: Image

HTML5 2011. 9. 7. 08:30
캔버스에서는 다순히 백터 그래픽만 표현할 수 있는 것이 아니라 이미지도 표현할 수 있습니다.

<div"><canvas id="c5" width="600" height = "300" style="border:solid 1px #000000;"></canvas>
<div>
<button onclick="draw_dragon();return true;">Draw Dragon</button>
<button onclick="draw_smaller_dragon();return true;">Draw smaller dragon</button>
<button onclick="draw_dragon_head();return true;">Draw Dragon Head</button>
<button onclick="Clear_image();return true;">Erase Everything</button>
</div>
</div>

<script>
  var c5 = document.getElementById("c5");
  var c5_context = c5.getContext("2d");

  var dragon = new Image();
  dragon.src = 'images/chinese_dragon.png';

  function draw_dragon() {
    c5_context.drawImage(dragon, 100, 5);
  }

  function draw_smaller_dragon() {
    c5_context.drawImage(dragon, 10, 5, 58, 100);
  }

  function draw_dragon_head() {
    c5_context.drawImage(dragon, 0, 19, 69, 97, 300, 100, 103, 145);
  }

  function Clear_image() {
    c5_context.clearRect(1, 1, 600, 300);
  }
</script>


drawImage는 이미지를 캔버스에 표현할 때 사용할 수 있습니다. 사용하는 방법은 먼저 Java Script에서 이미지 객체를 생성한 다음 실제 이미지가 존재하는 경로를 설정합니다. 

var dragon = new Image();
dragon.src = 'images/chinese_dragon.png';


이미지가 준비되었으면 drawImage()를 호출해서 캔버스에 이미지를 그리면 됩니다.
drawImage()는 3 가지 방법으로 사용할 수 있는데 3개의 인자를 사용하면 훈순히 이미지의 위치만 x, y로 지정할 수 있고 5개의 인자를 사용하면 출력할 이미지의 넓이와 높이를 지정할 수 있으며 마지막으로 9개의 인자를 사용하면 이미지의 일부를 표시할 수 있다.  

Overloading of drawImage() Description
3 arguments
drawImage (img,x,y)
img is the image element.
x and y being the coordinate to place the image object.
5 arguments
drawImage (img,x,y,width,height)
img is the image element.
x and y being the coordinate to place the image object. width and height will be image size that you want, resize as you want.
9 arguments
drawImage (img, crop_x, crop_y, crop_width, crop_height, x, y, width, height)
img is the image element.
crop_x and crop_y is where you start cropping your image.
crop_width and crop_height is the size you want to crop your image.
x and y still being the coordinate to place the image object.
width and height will be image size that you want, resize as you like it.

 


김영욱 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. 9. 6. 12:30

5.3 HTML5 Canvas: Path

HTML5 2011. 9. 6. 12:30
Path는 라인을 그릴때 사용 할 수 있습니다.

위와 같은 라인을 그리기 위해서 아래와 같은 코드가 필요 합니다.

<div><canvas id="Canvas2" width="600" height = "200" style="border:solid 1px #000000;"></canvas>
<div>
    <button onclick="Vertical_line();return true;">Click me to draw a brown vertical line</button></div>
</div>

<script>
   var c3 = document.getElementById("c3");
   var c3_context = c3.getContext("2d");

   function Vertical_line() {
     c3_context.
moveTo(300, 10);
     c3_context.lineTo(300, 190);
     c3_context.strokeStyle = "brown";
     c3_context.stroke();
   }
</script>

여기서 중요한 것이 moveTo, lineTo, strokeStyle, stroke()이다.
moveTo는 라인을 그리기 위해서 해당 위치로 포인트를 옮기는 역할을 한다. lineTo는 라인의 길이와 방향을 설정하고 strokeStyle에서 스타일을 설정한다.

실제 그림을 그리는 코드는 stroke() 이다.

method Descriptions
moveTo(x,y) move to starting point with coordinate x and y.
lineTo(x,y) Draw a line to this point from starting point. Again x and y being the coordinate.
strokeStyle CSS color of the line
stroke A method to actually make javascript draw a line
beginPath Before you start drawing a new line with different color, you will have to call "beginPath".



참 쉽죠?

김영욱 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. 9. 6. 08:30

5.2 HTML5 Canvas: Shadow

HTML5 2011. 9. 6. 08:30
지난번 글에서 캠퍼스에서 사각형을 어떻게 그릴 수 있는가에 대해서 정리를 했다면 이번 글에서는 사각형에 어떻게 그림자를 그리는 가에 대한 설명입니다.
 그림자를 그리는데에는 shadowOffSetX, shadowOffSetY, shadowBlur, shadowColor 이렇게 네개의 속성을 사용할 수 있습니다.

Context properties Descriptions
shadowOffsetX Horizontal distance (x-axis) between the shadow and the shape in pixel.
shadowOffsetY Vertical distance (y-axis) between the shadow and the shape in pixel.
shadowBlur How blur you want your shadow to be.
shadowColor Obviously, this is to set the color of your shadow

예제를 보면 확실히 쉽게 이해 될 것 같습니다.

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

<script>
var c8 = document.getElementById("c8");
var c8_context = c8.getContext("2d");

function draw_rectangle() {
c8_context.
shadowOffsetX = 5;
c8_context.
shadowOffsetY = 5;
c8_context.
shadowBlur = 10;
c8_context.shadowColor = "DarkGoldenRod";
c8_context.fillStyle = "Gold";
c8_context.fillRect(20, 20, 100, 120);
}
window.onload = draw_rectangle();
</script>

위의 예제를 보면 그림자의 위치는 X, Y 각각 5 만큼 공간을 띄우고 흐림의 정도를 10단계로 설정하고 컬러는 DarkGoldenRod로 지정하는 것을 볼 수 있습니다. 이에 따른 결과물은 다음과 같습니다.

깔끔하게 나오네요 ^^

김영욱 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. 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>
2011. 9. 1. 16:44

Smart Cloud Show 2011

News 2011. 9. 1. 16:44



오랫만에 탐나는 행사가 있어서 소개해 드립니다.
요즘 가장 빛나는 단어중에 하나인 스마트를 클라우드와 함께 생각해 볼 수 있는 행사 입니다.

자세한 내용은 http://www.facebook.com/smartcloudshow?sk=app_216854508325017#!/smartcloudshow?sk=app_208205529212473 에서 참조해 주세요.. ^^
2011. 9. 1. 12:30

4. HTML5 Video

HTML5 2011. 9. 1. 12:30


비디오와 관련된 태그도 오디오만큼이 사용하기 쉽습니다. 하지만 오디오와 마찬가지로 코덱이라는 문제는 여전히 가지고 있습니다.

<video src="rain.mp4" controls width="480" height="360"></video>

비디오와 관련해서는 추가적으로 넓이, 높이와 같은 추가적인 속성을 가지고 있습니다. 그런데 이렇게 쓰고나면 정말 이것으로 충분한가를 물어볼 분들이 많을 것 같습니다만 사실 이것이 다 입니다. HTML5는 요란하고 많은 사람들이 그 안에서 새로운 가능성을 찾아가고 있습니다만 사실 그 자체만 보면 그리 없지 않을 뿐만 아니라 상당히 쉬운 기술입니다.

 하지만 앞서 이야기 한 바와 같이 코덱과 라이선스라는 문제는 아직 여전히 남아 있습니다.

Browser H.264+
AAC+
MP4
WebM Theora
+Vorbis
+Ogg
Mozzila Firefox 3.6
Opera 10.63
Google Chrome 8.0
Apple Safari 5.0.3 (with QuickTime)
Microsoft IE 9 Beta


지금 현재 인터넷에서 비디오 파일을 만들 때 가장 많이 사용되고 있는 코덱이라면 H.264를 영상 코덱으로 하고 AAC를 음향 코덱으로 하는 확장자가 MP4인 파일입니다. 하지만 역시나 H.264 코덱의 경우도 상용 라이선스를 가지고 있는 코덱이기 때문에 FireFox, Opera에서는 현재 지원 하지 않고 있습니다.  
 WebM의 경우는 로열티 비용이 없는 개방형 고화질 영상 압축 포멧을 목표 구글의 후원을 받아 개발되고 잇습니다. 2010년 5월 19일 발표되었는데 주로 HTML5의 영상 포멧으로 많이 활용되고 있습니다. 현재로는 가장 많은 콘텐츠가 H.264로 되어 있지만 WebM을 지원하는 브라우저가 제일 많기 때문에 앞으로 시장 상황은 어떻게 진행될지 모르겠습니다.

비디오와 관련된 속성은 아래와 같습니다.
Attribute Value Description
controls *Boolean attribute If you want the browser native player control to be around, specifiy "controls"
autoplay *Boolean attribute If this guy exists, the browser will just play your video without asking permission from visitor
loop *Boolean attribute Keep repeating your video
src url The URL of your video file
preload none | metadata | auto This attribute was formerly known as "autobuffer" and it was an boolean attribute as "controls".

none - do not buffer video file automatically.
metadata - only buffer the metadata of video
auto - buffer video file before it gets played.
width width in pixels Width of video player
height height in pixels Height of video player
poster url of a image file If present, shows the poster image until the first frame of video has downloaded.

대부분의 속성은 오디오 태그와 동일한데 다른 점은 width, height, poster 입니다.
이 중에서 poster 속성은 비디오 파일이 로딩되기 전에 출력해주는 이미지 파일의 경로를 지정하는 속성으로 가급적이면 웹에서는 설정해 주는게 사용자들에게 좋은 접근이 될 것 같습니다.

김영욱 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. 9. 1. 08:30

3. HTML5 Audio

HTML5 2011. 9. 1. 08:30
초창기 웹에서는 HTML에 기반한 하이퍼링크 문서를 전달하는 용도로 설계되었기 때문에 오디오나 비디오 콘텐츠에 대한 배려나 표준안이 존재하지 않았습니다. 결국 표준안의 부재는 플러그인 기술의 발전으로 이어졌고 오디오와 비디오 재생을 위해서 윈도우 미디어 플래이어나 혹은 ActiveX 기반의 기술을 사용하는 방법 혹은 Silverlight나 Flash와 같은 RIA 기술이 사용하기도 했습니다.

 하지만 HTML5에서는 기본적으로 이와 관련해서 이미 준비되어 있는 태그가 정의되어 있고 별도의 플러그인이 없이 재생할 수 있게 되어 있습니다.


물론 각 브라우저 마다 보여주는 룩앤필은 조금씩 다르긴 하지만 미디어 재생에 있어서 일반적으로는 그게 인터페이스가 다르지 않기 때문에 문제 될 것은 없습니다.
 그럼 오디오를 사용하기 위해서는 어떻게 해야 할까요?

사용하는 방법 자체는 아주 간단합니다.

<audio src="vincent.mp3" controls></audio>

위와 같이 한 줄이면 해결 됩니다.
 여기서 한 가지 주의 할 점이 있는데 아직 해결되지 않은 문제가 코덱에 있다는 점입니다. HTML5의 표준안에는 태그는 정의되어 있지만 코덱까지는 표준으로 정해져 있지 않다는 점입니다. 여기에는 코덱을 사용하기 위해서 라이선스를 어떻게 할 것인가 하는 근본적인 문제가 있습니다. MP3의 경우도 독일 호퍼 연구소가 라이선스를 가지고 있어서 결코 '무료'는 아니기 때문 입니다.

Browser .mp3 .wav .ogg
Mozzila Firefox 3.6
Opera 10.63
Google Chrome 8.0
Apple Safari 5.0.3 (with QuickTime)
Microsoft IE 9

위의 표에서 볼 수 있다시피 FireFox나 Opera의 경우는 MP3를 지원하지 않습니다. 그 대신 오픈 라이선스 코덱인 OGG를 지원하고 있습니다. 이에 반해서 Chrome, Safari, IE9 등에서는 모두 MP3를 기본으로 설정하고 있습니다.

 물론 공통 분모로 WAV 방식을 사용할 수 있지만 압축되지 않은 데이터를 웹에서 다루는 것은 결코 좋은 방법이 아닙니다. 결국 제 생각에는 시간이 지나서 한 쪽으로 코덱이 정리되기를 기대하는 것이 지금 웹 개발자들이 할 수 있는 최선입니다. 하지만 지금 당장 어느 한쪽을 선택하라고 한 다면 저는 MP3쪽의 손을 들어주고 싶습니다.

아래표는 오디오와 관련된 태크와 함께 사용할 수 있는 속성을 정리한 표입니다.

Attribute Value Description
controls *Boolean attribute You need this to make the native audio player appear. Otherwise, you would have to use DOM to control the audio element to play your music.
autoplay *Boolean attribute If this guy exists, the browser will just play your song or your speech without asking permission from your visitor.
loop *Boolean attribute Keep repeating your music
src url The URL of your audio file
preload none | metadata | auto This attribute was formerly known as "autobuffer" and it was an boolean attribute as "controls".

none - do not buffer audio file automatically.
metadata - only buffer the metadata of audio file.
auto - buffer audio file before it gets played.

Controls 태그는 오디오를 제어할 수 있는 컨트롤의 표시 여부를 AutoPlay는 자동 재생 그리고 Loop는 무한 반복 여부를 나타냅니다. 실제 미디어의 경로는 Src로 표시할 수 있으며 재생전에 미리 버퍼링을 시작할 것이지를 결정하는 속성이 preload 입니다.

<audio src="vincent.mp3" controls="true" loop="true" autoplay="true"></audio>

실제로 태그를 보면 정말 간단해 졌습니다. 이전의 경우에는 Object 태그를 사용해서 복잡하게 다루어야 했지만 지금의 경우는 훨씬 더 간단해 졌다는 것을 알 수 있습니다.
 한 가지 추천해 드리고 싶은 것은 아직 HTML5를 지원하는 웹 브라우저가 많지 않기 때문에 그런 브라우저에 대한 배려를 잊지 말아야 하는 다는 점입니다. 

 마지막으로 Java Script에서 오디오를 제어하고 싶을 때는

<audio id="player" src="vincent.mp3"></audio>
<div>
   <button onclick="document.getElementById('player').play()">Play</button>
   <button onclick="document.getElementById('player').pause()">Pause</button>
   <button onclick="document.getElementById('player').volume += 0.1">Vol+ </button>
    <button onclick="document.getElementById('player').volume -= 0.1">Vol- </button>
</div>


와 같이 하시면 됩니다.


김영욱 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.09.13 15:15

    저기요.. 제가 지금 영욱님이 올리신 걸 보고 따라 했는데요..
    일시정지 버튼은 있는데 stop버튼은 없어서 그런데
    stop버튼 구현에 대한 방법도 가르쳐주실 수 있으신지요?

  • 글 잘 읽었습니다. 2012.02.22 14:34

    소스그대로 해보았는데요

    스트리밍이라서그런가요 컨트롤러가 안뜨네요 ㅠㅠ

    왜 그런것일까요 ㅎ