'HTML5'에 해당되는 글 18건

  1. 2012.05.15 HTML5 API - CORS(Cross Oragin Resource Sharing)
  2. 2012.05.11 HTML5 API - PostMessage
  3. 2012.05.11 HTML5 API - Geolocation
  4. 2012.05.10 HTML5 API - Video - 2
  5. 2012.05.09 HTML5 API - Video
  6. 2012.05.09 HTML5 API - Audio
  7. 2012.05.08 HTML5 API - Canvas - 2
  8. 2012.05.07 HTML5 API - Canvas - 1

HTML5 API - CORS(Cross Oragin Resource Sharing)


초기 Ajax 통신은 같은 도메인 간 컨텐츠 제어만 가능했었습니다. 


하지만 HTML5 명세의 "XMLHttpRequest Level 2" 사용 시 타 도메인 간 자원 공유

(Cross Oragin Resource Sharing(CORS))가 가능해 졌습니다.


즉, HTTP 요청 헤더에는 기존 통신 방식(Ajax)에 없었던 Origin 헤더가 포함되며, 이 헤더를 통해 송신자 측 도메인을 해당 서버에게 알려줍니다.


또한, 이 헤더는 브라우저에 의해 보호되며, 애플리케이션 코드로 변경할 수 없고, 이전 포스트인 "PostMessage API"에서 언급한 e.origin 속성과 동일한 기능을 합니다.



마지막으로 Origin 헤더의 또 한가지 특성으로는 이전 URL의 모든 경로를 포함하는 Reffer 헤더와는 달리 이 헤더는 브라우저로부터 무조건 전송됩니다.



P.S: Reffer 헤더는 전송 방식에 따라 헤더에 포함되지 않기도 합니다.(간단히 데이터 전송 시(GET, POST등..)는 포함되며, 기본적인 링크 이동 시에서는 포함되지 않습니다.)



이전 포스트에서 서버 측 "CORS"를 다루는 방법에 대해 설명 드렸습니다.


또한, 아래 코드는 이전 내용에서 다루지 못한 "CORS" 클라이언트 설계 부분입니다.




"CORS" 전송을 위한 수정된 AJAX API 모듈:


  1. var Ajax = (function (win, doc) {
  2.  
  3.     var ua = window.navigator.userAgent.toLowerCase();
  4.  
  5.     return { request: function (opt) { return new request(opt); } };
  6.  
  7.     // 요청
  8.     function request(opt) {
  9.  
  10.         this.options = {
  11.  
  12.             url: '',
  13.             type: 'html',
  14.             method: 'post',
  15.             headers: {},
  16.             data: {},
  17.             iscors: false,
  18.             onprogress: function () { ; },
  19.             onerror: function () { ; },
  20.             callback: function () { ; }
  21.         };
  22.  
  23.         extend.call(this.options, opt);
  24.  
  25.         // 크로스 도메인 전송 여부
  26.         this.options.iscors = isCORS.call(this.options);
  27.  
  28.         start.call(this.options);
  29.  
  30.         return this;
  31.     };
  32.  
  33.  
  34.     function start() {
  35.  
  36.         if (!this.url) return false;
  37.  
  38.         var xhr = getXHR.call(this)
  39.         , params = getParamsSerialize(this.data);
  40.  
  41.         // 크로스 도메인 전송 시
  42.         if (this.iscors) appendCORSEvents.call(this, xhr);
  43.  
  44.         var method = this.method = this.method.toLowerCase();
  45.  
  46.         var url = (method === 'get' && params) ? this.url + '?' + params + '&s=' + encodeURIComponent(new Date().toUTCString()) : this.url;
  47.  
  48.         xhr.open(method, url, true);
  49.  
  50.         // HTTP Header 추가
  51.         setHeaders.call(xhr, this.headers);
  52.  
  53.         (function ($this) { xhr.onreadystatechange = function () { handler.call($this, xhr); }; })(this);
  54.  
  55.         if (method === 'get' || method === 'head' || method === 'put' || method === 'delete' || method === 'options') xhr.send(null);
  56.         else if (method === 'post') xhr.send(params + '&s=' + encodeURIComponent(new Date().toUTCString()));
  57.     }
  58.  
  59.  
  60.     // xhr 객체 가져오기
  61.     function getXHR() {
  62.         /*
  63.         ie5.5+: MiCORSoft.XMLHTTP,
  64.         ie6+: Msxml2.XMLHTTP,
  65.         ie7+ or 표준 브라우저: XMLHttpRequest(), XDomainRequest()(cors 지원 브라우저)
  66.         표준 브라우저: XMLHttpRequest()
  67.         */
  68.  
  69.         return !window.XMLHttpRequest ? new ActiveXObject(ua.indexOf('msie 5') > -1 ? 'MiCORSoft.XMLHTTP' : 'Msxml2.XMLHTTP')
  70.         : this.iscors && window.XDomainRequest ? new window.XDomainRequest()
  71.         : window.XMLHttpRequest ? new XMLHttpRequest() : null;
  72.     };
  73.  
  74.     // CORS 사용 여부
  75.     function isCORS() {
  76.  
  77.         var url = this.url.replace(/(https:\/\/|http:\/\/)/, '');
  78.  
  79.         if (url.indexOf('/') > -1) url = url.substr(0, url.indexOf('/'));
  80.         else url = url.substr(0, url.length);
  81.        
  82.         return top.location.host !== url;
  83.     }
  84.  
  85.     // CORS 사용 시 해당 이벤트 핸들러 할당
  86.     function appendCORSEvents(x) {
  87.  
  88.         var that = this;
  89.  
  90.         if (window.XDomainRequest) {
  91.             x.onload = function () { that.callback.apply(x, [getXhrData.call(that, x), x.status]); };
  92.             x.onprogress = this.onprogress;
  93.             x.onerror = this.onerror;
  94.  
  95.  
  96.         }
  97.         else if (typeof x.withCredentials !== 'undefined') {
  98.             bind(x, 'load', function () { that.callback.apply(x, [getXhrData.call(that, x), x.status]); });
  99.             //bind(x, 'progress', function (e) { that.onprogress.apply(x, [e, e.total, e.loaded, (parseFloat(e.loaded / e.total) * 100), e.lengthComputable]) });
  100.             bind(x.upload, 'progress', function (e) { that.onprogress.apply(x, [e, e.total, e.loaded, (parseFloat(e.loaded / e.total) * 100), e.lengthComputable]) });
  101.             bind(x, 'error', this.onerror);
  102.         }
  103.     }
  104.  
  105.     // 파라메터 직렬화
  106.     function getParamsSerialize(data) {
  107.  
  108.         var ret = [];
  109.  
  110.         for (var p in data) ret.push(p + '=' + encodeURIComponent(data[p]));
  111.  
  112.         return ret.join('&');
  113.     };
  114.  
  115.     // 요청 헤더 추가
  116.     function setHeaders(headers) {
  117.         if (this.iscors) headers['X-Requested-With'] = 'XMLHttpRequest';
  118.         if (this.setRequestHeader) for (var h in headers) if (headers[h] !== '') this.setRequestHeader(h, headers[h]);
  119.     };
  120.  
  121.     // 응답 헨들러
  122.     function handler(x) {
  123.  
  124.         if (!this.iscors && x.readyState === 4) {
  125.             if (error(x.status)) alert('request Error status:' + x.status);
  126.             else this.callback.apply(x, [getXhrData.call(this, x), x.status]);
  127.         }
  128.     };
  129.  
  130.  
  131.     // 서버 에러 유/무
  132.     function error(s) {
  133.  
  134.         return !s && window.location.protocol === 'file:' ? false : s >= 200 && s < 300 ? false : s === 304 ? false : true;
  135.     };
  136.  
  137.     // 수신받은 결과값 가공 함수
  138.     function getXhrData(x) {
  139.  
  140.         var contentType = ''
  141.             , xml = false
  142.             , json = false;
  143.  
  144.         if (x.getResponseHeader){
  145.             contentType = x.getResponseHeader('content-type')
  146.             xml = contentType && contentType.indexOf('xml') > -1
  147.             json = contentType && contentType.indexOf('json') > -1;
  148.         }
  149.  
  150.         var type = this.type.toLowerCase();
  151.  
  152.         if (xml && type === 'xml') return x.responseXML;
  153.         else if (json && type === 'json') return eval('(' + x.responseText + ')');
  154.         else if (type === 'text') return x.responseText.replace(/<(\/)?([a-zA-Z]*)(\s[a-zA-Z]*=[^>]*)?(\s)*(\/)?>/g, '');
  155.         else return x.responseText;
  156.  
  157.     };
  158.  
  159.     // 객체 상속 함수
  160.     function extend() {
  161.  
  162.         var target = this
  163.         , opts = []
  164.         , src = null
  165.         , copy = null;
  166.  
  167.         for (var i = 0, length = arguments.length; i < length; i++) {
  168.  
  169.             opts = arguments[i];
  170.  
  171.             for (var n in opts) {
  172.                 src = target[n];
  173.                 copy = opts[n];
  174.  
  175.                 if (src === copy) continue;
  176.                 if (copy) target[n] = copy;
  177.             }
  178.         }
  179.     };
  180.  
  181. })(window, document);



실행코드:


  1. function ajax()
  2. {
  3.  
  4.     Ajax.request({
  5.         //url: 'http://m.fpscamp.com/main/index.aspx',
  6.         //url: 'http://m.fpscamp.com',
  7.         url: 'http://sof.fpscamp.com/sof.aspx',
  8.         type: 'text',
  9.         method: 'post',
  10.         headers: {
  11.             'content-type': 'application/x-www-form-urlencoded'
  12.         },
  13.         data: {
  14.             id: 'id1'
  15.         },
  16.         onprogress: function (e, total, loaded, per, computable) {
  17.             alert(e); // 이벤트
  18.             alert(total); // 전체 데이터 크기
  19.             alert(loaded); // 전송된  데이터 크기
  20.             alert(per); // 전송된 데이터 크기(percent)
  21.             alert(computable); // 전체 데이터 크기를 알고 있는지 여부
  22.         },
  23.         onerror: function () {
  24.             alert('onerror');
  25.         },
  26.         callback: function (data, status) {
  27.             alert(data);
  28.             //alert(status);
  29.         }
  30.     });
  31. };
  32.  
  33. // 이벤트 할당
  34. function bind(elem, type, handler, capture) {
  35.     type = typeof type === 'string' && type || '';
  36.     handler = handler || function () { ; };
  37.  
  38.     if (elem.addEventListener) {
  39.         elem.addEventListener(type, handler, capture);
  40.     }
  41.     else if (elem.attachEvent) {
  42.         elem.attachEvent('on' + type, handler);
  43.     }
  44.  
  45.     return elem;
  46. };






- 아래는 이전 모듈에서 수정 및 추가 된 부분입니다.



CORS 전송 유/무를 가리기 위해 "로컬 도메인"과 사용자로부터 전달된 "요청 도메인"을 비교하는 함수입니다.


  1. // CROS 사용 여부
  2. function isCORS(){
  3.  
  4.     var url = this.url.replace(/(https:\/\/|http:\/\/)/, '');
  5.  
  6.     if (url.indexOf('/') > -1) url = url.substr(0, url.indexOf('/'));
  7.     else url = url.substr(0, url.length);
  8.        
  9.     return top.location.host !== url;
  10. }




CORS 전송 시 IE8+ 및 각종 표준 브라우저의 XHR 객체에 이벤트 핸들러를 할당합니다.


  1. // CORS 사용 시 해당 이벤트 핸들러 할당
  2. function appendCORSEvents(x) {
  3.  
  4.     var that = this;
  5.  
  6.     if (window.XDomainRequest) {
  7.         x.onload = function () { that.callback.apply(x, [getXhrData.call(that, x), x.status]); };
  8.         x.onprogress = this.onprogress;
  9.         x.onerror = this.onerror;
  10.  
  11.  
  12.     }
  13.     else if (typeof x.withCredentials !== 'undefined') {
  14.         bind(x, 'load', function () { that.callback.apply(x, [getXhrData.call(that, x), x.status]); });
  15.         //bind(x, 'progress', function (e) { that.onprogress.apply(x, [e, e.total, e.loaded, (parseFloat(e.loaded / e.total) * 100), e.lengthComputable]) });
  16.         bind(x.upload, 'progress', function (e) { that.onprogress.apply(x, [e, e.total, e.loaded, (parseFloat(e.loaded / e.total) * 100), e.lengthComputable]) });
  17.         bind(x, 'error', this.onerror);
  18.     }
  19. }



IE8+ 브라우저에서는 xhr.setRequestHeader() 메서드를 지원하지 않으며, CORS 전송 시 커스텀 헤더인 "X-Requested-With" 헤더를 사용할 수 없습니다.    


  1. // 요청 헤더 추가
  2. function setHeaders(headers) {
  3.     if (this.iscros) headers['X-Requested-With'] = 'XMLHttpRequest';
  4.     if (this.setRequestHeader) for (var h in headers) if (headers[h] !== '') this.setRequestHeader(h, headers[h]);
  5. };



setHeaders() 메서드와 마찬가지로 IE8+ 브라우저에서는 xhr.getResponseHeader () 메서드 또한 지원하지 않습니다.


  1. // 수신받은 결과값 가공 함수
  2. function getXhrData(x) {
  3.  
  4.     var contentType = ''
  5.         , xml = false
  6.         , json = false;
  7.  
  8.     if (x.getResponseHeader){
  9.         contentType = x.getResponseHeader('content-type')
  10.         xml = contentType && contentType.indexOf('xml') > -1
  11.         json = contentType && contentType.indexOf('json') > -1;
  12.     }
  13.  
  14.     var type = this.type.toLowerCase();
  15.  
  16.     if (xml && type === 'xml') return x.responseXML;
  17.     else if (json && type === 'json') return eval('(' + x.responseText + ')');
  18.     else if (type === 'text') return x.responseText.replace(/<(\/)?([a-zA-Z]*)(\s[a-zA-Z]*=[^>]*)?(\s)*(\/)?>/g, '');
  19.     else return x.responseText;
  20.  
  21. };




HTML5 API - PostMessage



HTML5에서는 postMessage API와 XMLHttpRequest 레벨2 같은 새로운 통신 방식이 추가됐으며, 이로써 기존 보안 정책상의 이유로 허용되지 않았던 타 도메인과의 통신 또한 가능해졌습니다.


또한, 기존의 보안정책을 개선한 이유는 컨텐츠 전송방식이 현 트랜드와 맞지 않았기 떄문이었습니다.

예를 들면, 타 사이트의 컨텐츠를 가공하여 새로운 컨텐츠를 생산하는 매시업과 같은 기능을 구현하는데 어려움이 많았다는 것이었습니다.




postMessage API 사용방법:



1. 송신 페이지


- iframe 객체가 포함하는 페이지(http://sof.fpscamp.com/sof.htm)에 해당 데이터를 postMessage 메서드를 이용하여 전송한다.


  1. document.getElementById('sof').contentWindow.postMessage(document.getElementById('requestMsg').value, 'http://sof.fpscamp.com');


- 송신 페이지에 포함된 iframe(http://sof.fpscamp.com/sof.htm) 객체

  1. <div><iframe id="sof" name="sof" src="http://sof.fpscamp.com/sof.htm?12312312" width="1000" height="1000"></iframe></div>


2. 수신 페이지

window 객체 이벤트인 onmessage 이벤트 핸들러를 할당하여 송신자의 요청을 처리한다.

1. e.origin: 송신자의 도메인을 반환한다.(해당 속성으로 무작위로 전송되는 데이터 처리를 제한시킨다.(허용 도메인만 처리))

2. e.data: 송신자의 데이터를 반환한다.


  1.      bind(window, 'message', function (e) {
  2.         if (e.origin === 'http://m.fpscamp.com') {
  3.             document.getElementById('msg_list').innerHTML += '<li style="margin-top:4px;">' + e.data + '(' + e.origin + ' 도메인에서 메시지를 전송함)</li>';            
  4.         }
  5.     });




아래는 postMessage API를 활용한 타 도메인간의 전송 방법을 다룬 코드 예제입니다.


- 송신 페이지(http://m.fpscamp.com)

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>postMessage</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.     bind(window, 'message', function (e) {
  11.         if (e.origin === 'http://sof.fpscamp.com') {
  12.             document.getElementById('msg_list').innerHTML += '<li style="margin-top:4px;">' + e.data + '(' + e.origin + ' 도메인에서 메시지를 전송함)</li>';
  13.         }
  14.     });
  15.  
  16.     function sendMsg() {
  17.         document.getElementById('sof').contentWindow.postMessage({}, 'http://sof.fpscamp.com');
  18.     }
  19.  
  20.     // 이벤트 할당
  21.     function bind(elem, type, handler, capture) {
  22.         type = typeof type === 'string' && type || '';
  23.         handler = handler || function () { ; };
  24.  
  25.         if (elem.addEventListener) {
  26.             elem.addEventListener(type, handler, capture);
  27.         }
  28.         else if (elem.attachEvent) {
  29.             elem.attachEvent('on' + type, handler);
  30.         }
  31.  
  32.         return elem;
  33.     };
  34.  
  35.  
  36. //]]>
  37. </script>
  38. <input type="text" id="requestMsg" />
  39. <input type="button" value="postMessage" onclick="sendMsg()" />
  40.  
  41. <div id="text_container" style="width:100%;height:100%"><ul id="msg_list"></ul></div>
  42.  
  43. <div><iframe id="sof" name="sof" src="http://sof.fpscamp.com/sof.htm?12312312" width="1000" height="1000"></iframe></div>
  44. </body>
  45. </html>



- 수신 페이지(http://sof.fpscamp.com)

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>postMessage</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     bind(window, 'message', function (e) {
  12.         if (e.origin === 'http://m.fpscamp.com') {
  13.             document.getElementById('msg_list').innerHTML += '<li style="margin-top:4px;">' + e.data + '(' + e.origin + ' 도메인에서 메시지를 전송함)</li>';            
  14.         }
  15.     });
  16.  
  17.     function sendMsg() {
  18.         top.window.postMessage(document.getElementById('responseMsg').value, 'http://m.fpscamp.com');
  19.     }
  20.  
  21.     // 이벤트 할당
  22.     function bind(elem, type, handler, capture) {
  23.         type = typeof type === 'string' && type || '';
  24.         handler = handler || function () { ; };
  25.  
  26.         if (elem.addEventListener) {
  27.             elem.addEventListener(type, handler, capture);
  28.         }
  29.         else if (elem.attachEvent) {
  30.             elem.attachEvent('on' + type, handler);
  31.         }
  32.  
  33.         return elem;
  34.     };
  35.  
  36.  
  37. //]]>
  38. </script>
  39. <input type="text" id="responseMsg" />
  40. <input type="button" value="serMessage" onclick="sendMsg()" />
  41.  
  42. <div id="text_container" style="width:100%;height:100%"><ul id="msg_list"></ul></div>
  43. </body>
  44. </html>

한 가지 유념할 부분으로는 컨텐츠에 접근하는 도메인이 서로 다르다는 것입니다. (postMessage API의 핵심요소)



페이지 실행결과:






HTML5 API - Geolocation


HTML5 API 중 지오로케이션(위치기반서비스)이라는 기능이 존재하며, 사용자 위치요청에 동의한 경우 브라우저가 위치 정보(위도, 경도 등..)를 반환합니다.


즉, 지오로케이션을 지원하는 브라우저가 실행 중인 스마트폰과 같은 여러 모바일 기기에서 위치 정보를 브라우저에게 전달하는 것입니다.



- 위치 정보를 알아오는 방법으로는 아래와 같이 총 4가지 방법이 존재합니다.


1. IP 주소 기반 데이터: 어디서나 사용 가능하나 정확도가 매우 낮다.


2. GPS 기반 지오로케이션 데이터: 매우 정확하다는 장점이 있지만, 위치 정보 판단을 위해 시간이 오래 소요되며, 그만큼 기기의 베터리를 소모한다.


3. Wi-Fi 기반 지오로케이션 데이터: 정확하나 무선 AP가 적은 지역에서는 정확도가 떨어진다.


4. 휴대전화 지오로케이션 데이터: 어느 정도 정확하나 기지국이 적은 지역에서는 정확도가 떨어진다.





지오로케이션 브라우저 지원 현황:






마지막으로 아래는 소스는 지오로케이션을 통해 받아온 위치정보를 구글맵과 연동하여, 현재 자신의 위치를 지도상에 표시하는 간단한 예제입니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>GeoLocation</title>
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  6.     <meta charset="UTF-8">
  7.     <style type="text/css">
  8.     /*<[CDATA[*/
  9.  
  10.         html, body, #map_canvas {
  11.             margin: 0;
  12.             padding: 0;
  13.             height: 100%;
  14.         }
  15.     /*]]>*/
  16.     </style>
  17. </head>
  18. <body>
  19. <script type="text/javascript">
  20. //<![CDATA[
  21.  
  22.     bind(window, 'load', function () {
  23.         geolocationInit();
  24.     });
  25.  
  26.     // 이벤트 할당
  27.     function bind(elem, type, handler, capture) {
  28.         type = typeof type === 'string' && type || '';
  29.         handler = handler || function () { ; };
  30.  
  31.         if (elem.addEventListener) {
  32.             elem.addEventListener(type, handler, capture);
  33.         }
  34.         else if (elem.attachEvent) {
  35.             elem.attachEvent('on' + type, handler);
  36.         }
  37.  
  38.         return elem;
  39.     };
  40.  
  41.  
  42.  
  43.     function geolocationInit() {
  44.  
  45.         if (navigator.geolocation) {
  46.             var geo = navigator.geolocation;
  47.             geo.getCurrentPosition(function (pos) {
  48.                 // 위도
  49.                 //alert(pos.coords.latitude);
  50.                 // 경도
  51.                 //alert(pos.coords.longitude);
  52.                 // 정확도
  53.                 //alert(pos.coords.accuracy);
  54.                 // 마지막 업데이트 시간(초)
  55.                 //alert(pos.timestamp);
  56.  
  57.                 // google map 연동
  58.                 mapInit(pos.coords.latitude, pos.coords.longitude);
  59.  
  60.             }, function (e) {
  61.                 msg({
  62.                     0: '위치 정보 검색에 문제가 있습니다.(msg:' + e.message + ')',
  63.                     1: '현재 페이지에서 사용자가 위치 정보 검색을 거부했습니다.',
  64.                     2: '브라우저가 위치정보를 검색하지 못했습니다.(msg:' + e.message + ')',
  65.                     3: '브라우저의 위치 정보 검색 시간이 초과됐습니다.'
  66.                 }[e.code]);
  67.  
  68.             }, {
  69.                 enableHeighAccuracy: false,
  70.                 timeout: 10000,
  71.                 maximumAge: 0
  72.             });
  73.  
  74.             /*
  75.  
  76.             var watchid = geo.watchCurrentPosition(updatecallback, errorcallback, opt): 위치정보검색을 반복한다.
  77.             geo.clearWatch(watchid): 위치정보검색 반복을 중지한다.
  78.  
  79.             enableHeighAccuracy: HTML5 지오로케이션 서비스가 고도 정확도 감지모드를 사용할 수 있는지 여부를 브라우저에게 알려준다.
  80.             하지만 이 기능을 활성화하면 위치를 파악하느라 더 많은 시간과 전력이 소모된다.(기본값: false)
  81.  
  82.             timeout: 위치 정보를 계산하는 시간을 의미하며, 정의된 시간이 넘어가면 에러를 발생시킨다.
  83.  
  84.             maximumAge: 현 위치 정보에 대한 만료시간을 정의합니다.
  85.  
  86.  
  87.  
  88.  
  89.             */
  90.         }
  91.         else {
  92.             alert('HTML 5 지오로케이션을 지원하지 않는 브라우저입니다.');
  93.         }
  94.     }
  95.  
  96.     function msg(msg) {
  97.         alert(msg);
  98.     }
  99.  
  100.  
  101. //]]>
  102. </script>
  103. <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
  104. <script type="text/javascript">
  105. //<![CDATA[
  106.  
  107.     function mapInit(latitude, longitude) {
  108.         var opt = {
  109.             zoom: 15,
  110.             center: new google.maps.LatLng(latitude, longitude),
  111.             mapTypeId: google.maps.MapTypeId.ROADMAP
  112.         };
  113.  
  114.         var map = new google.maps.Map(document.getElementById('map_canvas'), opt);
  115.     };
  116. //]]>
  117. </script>
  118. <div id="map_canvas"></div>
  119. </body>
  120. </html>


모바일 기기 실행결과:






크지 않은 오차범위로 현재 저의 위치정보를 정확하게 가져오는 것을 확인할 수 있습니다.



참고사이트:


레퍼런스: 

http://www.w3schools.com/html5/html5_geolocation.asp


브라우저 지원현황

http://caniuse.com/




HTML5 API - Video - 2


Canvas 객체의 기능 중 앞서 배운 Video 객체와 연동 가능하며, 응용범위 또한 큰 기능에 대해 설명 드리도록 하겠습니다.


객체 맴버인 drawImage() 메서드를 활용한 방법이며, Image 객체 대신 Video 객체를 인자 값으로 전달하여 해당 프레임의 이미지를 캔버스에 노출시킬 수 있는 기능입니다.


미디어클립의 이미지 프레임을 캡쳐하는 코드는 아래와 같습니다.


- this.player(Video 객체)


  1. ctx.drawImage(this.player, 0, 0, this.width, this.height, 0, 0, this.width, this.height);


또한, 아래 코드는 이전 포스트의 Video API를 응용하여, 원본(미디어 클립), 캔버스(재생 중인 이미지를 노출시킬 캔버스), 복사본(저장된 이미지 배열을 노출시킬 캔버스)을 생성하여 재생 중인 원본(미디어클립) 이미지 프레임을 캔버스에 노출시키고, 저장된 이미지 프레임을 배열로 만들어 Canvas 객체의 getImageData(), putImageData() 를 활용하여 복사본 캔버스에 다시 한번 노출시킵니다.(녹화 기능)




- 왼쪽(미디어클립), 중앙(재생 캔버스), 오른쪽(녹화 캔버스)



전체 소스는 아래와 같습니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Video</title>
  5.     <style type="text/css">
  6.        
  7.     * html
  8.     {
  9.         margin:0;
  10.         padding:0;
  11.     }
  12.    
  13.    
  14.     body
  15.     {
  16.         width:100%;
  17.         height:100%;
  18.     }
  19.     </style>
  20. </head>
  21. <body>
  22. <script type="text/javascript">
  23. //<![CDATA[
  24.  
  25.     var Video = (function (win, doc) {
  26.  
  27.         return function (opt) {
  28.  
  29.             function init() {
  30.  
  31.                 this.options = {
  32.                     player: null,
  33.  
  34.                     wrap: null,
  35.  
  36.                     id: '',
  37.                     src: '',
  38.                     poster: '',
  39.                     width: 500,
  40.                     height: 344,
  41.                     autoplay: false,
  42.                     controls: false,
  43.                     loop: false,
  44.                     isloaded: false,
  45.                     onload: function () { ; },
  46.                     onplay: function () { ; },
  47.                     onprogress: function () { ; },
  48.                     ontimeupdate: function () { ; },
  49.                     onended: function () { ; },
  50.                     onerror: function () { ; }
  51.  
  52.                 };
  53.  
  54.                 extend.call(this.options, opt);
  55.  
  56.                 // audio load
  57.                 load.call(this.options);
  58.  
  59.                 return this;
  60.             }
  61.  
  62.             Video.fn = init.prototype = {
  63.                 play: play,
  64.                 stop: stop,
  65.                 isEnded: isEnded,
  66.                 getTimeout: getTimeout,
  67.                 getStartTime: getStartTime,
  68.                 getSrc: getSrc,
  69.                 isBuffering: isBuffering,
  70.                 getCurrentTimeout: getCurrentTimeout,
  71.                 setVolume: setVolume,
  72.                 setMuted: setMuted,
  73.                 getVideoSize: getVideoSize
  74.  
  75.             }
  76.  
  77.             return new init();
  78.         };
  79.  
  80.         // audio 객체를 생성한다.
  81.         function createElement() {
  82.  
  83.             this.player = document.createElement('video');
  84.             this.player.id = this.id;
  85.             this.player.src = this.src;
  86.  
  87.             // 미디어 클립이 로드되는 동안 컨텐츠 대신 보여질 이미지 파일의 URL을 지정한다.
  88.             this.player.poster = this.poster;
  89.             // 미디어 클립의 가로폭
  90.             this.player.width = this.width;
  91.             // 미디어 클립의 세로폭
  92.             this.player.height = this.height;
  93.  
  94.             this.player.autoplay = this.autoplay;
  95.             this.player.controls = this.controls;
  96.             this.player.loop = this.loop;
  97.  
  98.             var that = this;
  99.  
  100.             // 미디어클립을 재생할 준비가 완료 시 이벤트 핸들러
  101.             bind(this.player, 'canplay', function () {
  102.  
  103.                 that.onload.call(null);
  104.                 this.isloaded = true;
  105.             });
  106.  
  107.             // 미디어클립 재생 클릭 시 이벤트 핸들러
  108.             bind(this.player, 'play', function () { that.onplay(); });
  109.             // 브라우저가 미디어클립 데이터를 가져오는 프로세스에 있을 시 이벤트 핸들러
  110.             bind(this.player, 'progress', function () { that.onprogress(); });
  111.             // 미디어 클립 재생 시 지속적으로 발생(재생 위치가 변경되었을때)
  112.             bind(this.player, 'timeupdate', function () { that.ontimeupdate(); });
  113.             // 미디어 클립 종료 시 이벤트 핸들러
  114.             bind(this.player, 'ended', function () { that.onended(); });
  115.             // 미디어 클립 로드 오류 시 이벤트 핸들러
  116.             bind(this.player, 'error', function () { that.onerror(); });
  117.  
  118.             return this.player;
  119.         };
  120.  
  121.         // audio 객체를 로드합니다.
  122.         function load() {
  123.  
  124.             var elem = createElement.call(this);
  125.  
  126.             if (elem.load) (this.wrap || document.body).appendChild(elem);
  127.             else alert('Video 객체를 지원하지 않는 브라우저 입니다.');
  128.         };
  129.  
  130.         // 미디어클립을 재생합니다.
  131.         function play() {
  132.  
  133.             this.options.player.play();
  134.  
  135.             return this;
  136.         };
  137.  
  138.         // 미디어클립 재생을 중지합니다.
  139.         function stop() {
  140.  
  141.             !this.options.player.paused && this.options.player.pause();
  142.             return this;
  143.         }
  144.  
  145.         // 미디어클립 재생 여부를 반환
  146.         function isEnded() {
  147.             return this.options.player.ended;
  148.         };
  149.  
  150.  
  151.         // 미디어클립의 총 재생시간을 반환
  152.         function getTimeout(type) {
  153.  
  154.             type = type || 'hours';
  155.  
  156.             return {
  157.                 'second': this.options.player.startTime,
  158.                 'hours': getDateSecondToHours(this.options.player.duration)
  159.             }[type];
  160.         };
  161.  
  162.         // 미디어클립의 현재 재생시간을 반환
  163.         function getCurrentTimeout(type) {
  164.  
  165.             type = type || 'hours';
  166.  
  167.             return {
  168.                 'second': this.options.player.currentTime,
  169.                 'hours': getDateSecondToHours(this.options.player.currentTime)
  170.             }[type];
  171.         };
  172.  
  173.         // 미디어 클립의 현재 재생 시간을 반환
  174.         // 0.0(min) ~ 1(max) 할당한다.
  175.         function setVolume(num) {
  176.  
  177.             num = num || 0;
  178.  
  179.             this.options.player.volume = num / 10;
  180.  
  181.             return this;
  182.         };
  183.  
  184.         // 음소거 여부를 설정한다.
  185.         function setMuted(b) {
  186.  
  187.             b = b || false;
  188.  
  189.             this.options.player.muted = b;
  190.  
  191.             return this;
  192.         };
  193.  
  194.         // 미디어 클립이 재생을 시작할 수 있는 가능한 가장 빠른 시간을 반환합니다.
  195.         // 미디어 클립이 스트리밍되거나, 버퍼링되지 않으면 0을 반환합니다.
  196.         function getStartTime(type) {
  197.  
  198.             return this.options.player.startTime;
  199.         };
  200.  
  201.         // 현재 버퍼링 상태 여부를 반환
  202.         function isBuffering() {
  203.             return this.options.player.startTime !== 0;
  204.         };
  205.  
  206.         // 현재 재생중인 파일명을 반환합니다.
  207.         function getSrc() {
  208.             return this.options.player.currentSrc;
  209.         };
  210.  
  211.         // 미디어클립의 사이즈를 반환한다.
  212.         function getVideoSize() {
  213.             return {
  214.                 w: this.options.player.videoWidth,
  215.                 h: this.options.player.videoHeight
  216.             }
  217.         }
  218.  
  219.  
  220.         function getDateSecondToHours(i) {
  221.  
  222.             i = i || 0;
  223.  
  224.             var h = parseInt(((i / 3600) % 24), 10)
  225.               , m = parseInt(((i / 60) % 60), 10)
  226.               , s = parseInt(((i / 1) % 60), 10);
  227.  
  228.             h = h < 10 ? '0' + h : h;
  229.             m = m < 10 ? '0' + m : m;
  230.             s = s < 10 ? '0' + s : s;
  231.  
  232.             return h + ':' + m + ':' + s;
  233.         };
  234.  
  235.         // 객체 상속 함수
  236.         function extend() {
  237.  
  238.             var target = this
  239.           , opts = []
  240.           , src = null
  241.           , copy = null;
  242.  
  243.             for (var i = 0, length = arguments.length; i < length; i++) {
  244.  
  245.                 opts = arguments[i];
  246.  
  247.                 for (var n in opts) {
  248.                     src = target[n];
  249.                     copy = opts[n];
  250.  
  251.                     if (src === copy) continue;
  252.                     if (copy) target[n] = copy;
  253.                 }
  254.             }
  255.         };
  256.  
  257.  
  258.     })(window, document);
  259.  
  260.  
  261.     bind(window, 'load', function () {
  262.  
  263.         p1 = Video({
  264.             id: 'video_test1',
  265.             src: 'http://m.fpscamp.com/test.mp4',
  266.             wrap: document.getElementById('container'),
  267.             poster: 'http://static.naver.net/www/u/2010/0611/nmms_215646753.gif',
  268.             autoplay: true,
  269.             controls: true,
  270.             loop: false,
  271.             onload: function () {
  272.             },
  273.             onplay: function () {
  274.                
  275.                 // 캔버스
  276.                 var canvas = createCanvasElement.call(this, 'canvas_test');
  277.                 // 복사본 캔버스
  278.                 var canvas_copy = createCanvasElement.call(this, 'canvas_copy');
  279.  
  280.                 var that = this;
  281.                 t = window.setInterval(function () {
  282.                     if (!that.player.paused) {
  283.                         updateFrame.call(that, canvas);
  284.                     }
  285.                     else {
  286.                         window.clearInterval(t);
  287.                     }
  288.                 }, 60);
  289.             },
  290.             onprogress: function () {
  291.             },
  292.             ontimeupdate: function () {
  293.             },
  294.             onended: function () {
  295.  
  296.                 window.clearInterval(t);
  297.                 var frameLength = 0;
  298.  
  299.                 (function () {
  300.                     // 원본 재생이 끝내면, 배열에 저장된 이미지를 복사본 캔버스에 재생시킵니다.
  301.                     frameTimerId = window.setInterval(function () {
  302.                         if (frameLength < frames.length) {
  303.                             document.getElementById('canvas_copy').getContext('2d').putImageData(frames[frameLength], 0, 0);
  304.                             frameLength++;
  305.                         }
  306.                         else {
  307.                             window.clearInterval(frameTimerId);
  308.                         }
  309.                     }, 60);
  310.                 })();
  311.             },
  312.             onerror: function () {
  313.                 alert(this === window);
  314.             }
  315.         });
  316.     });
  317.  
  318.     var canvas = null
  319.       , ctx = null;      
  320.     function createCanvasElement(id) {
  321.  
  322.         id = id || '';
  323.  
  324.         var elem = document.getElementById(id);
  325.  
  326.         if (!elem) {
  327.             elem = document.createElement('canvas');
  328.  
  329.             elem.id = id;
  330.             elem.width = this.width;
  331.             elem.height = this.height;
  332.  
  333.             document.getElementById('container').appendChild(elem);
  334.  
  335.             return elem;
  336.         }
  337.         else {
  338.             return elem;
  339.         }
  340.     }
  341.  
  342.     var frames = []
  343.       , frameTimerId = null;
  344.     function updateFrame(canvas) {
  345.  
  346.         ctx = canvas.getContext('2d');
  347.         ctx.drawImage(this.player, 0, 0, this.width, this.height, 0, 0, this.width, this.height);
  348.  
  349.         var pxs = ctx.getImageData(0, 0, this.width, this.height);
  350.  
  351.         frames.push(pxs);
  352.     }
  353.  
  354.     // 이벤트 할당
  355.     function bind(elem, type, handler, capture) {
  356.         type = typeof type === 'string' && type || '';
  357.         handler = handler || function () { ; };
  358.  
  359.         if (elem.addEventListener) {
  360.             elem.addEventListener(type, handler, capture);
  361.         }
  362.         else if (elem.attachEvent) {
  363.             elem.attachEvent('on' + type, handler);
  364.         }
  365.  
  366.         return elem;
  367.     };
  368.  
  369. //]]>
  370. </script>
  371. <input id="" type="button" value="play" onclick="p1.play()" />
  372. <input id="" type="button" value="stop" onclick="p1.stop()" />
  373. <input id="" type="button" value="isEnded" onclick="alert(p1.isEnded())" />
  374. <input id="" type="button" value="getTimeout" onclick="alert(p1.getTimeout())" />
  375. <input id="" type="button" value="getStartTime" onclick="alert(p1.getStartTime())" />
  376. <input id="" type="button" value="getSrc" onclick="alert(p1.getSrc())" />
  377. <input id="" type="button" value="isBuffering" onclick="alert(p1.isBuffering())" />
  378. <input id="" type="button" value="getCurrentTimeout" onclick="alert(p1.getCurrentTimeout())" />
  379. <input id="" type="button" value="setVolume" onclick="p1.setVolume(5)" />
  380. <input id="" type="button" value="setMuted" onclick="p1.setMuted(true)" />
  381. <input id="Button1" type="button" value="getVideoSize(width)" onclick="alert(p1.getVideoSize().w)" />
  382. <input id="Button2" type="button" value="getVideoSize(height)" onclick="alert(p1.getVideoSize().h)" />
  383. <div id="container">
  384. </div>
  385. </body>
  386. </html>




HTML5 API - Video



아래는 지난 포스트에 이어 Video 객체의 모든 기능을 모듈화 시킨 코드이며, 추가된 몇 가지 맴버(poster, width, height, onended)를 제외한 나머지는 Audio 객체의 맴버와 동일합니다.


아래 소스를 이용하여 Video 객체의 모든 기능을 테스트 하실 수 있습니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Video</title>
  5.     <style type="text/css">
  6.        
  7.     * html
  8.     {
  9.         margin:0;
  10.         padding:0;
  11.     }
  12.    
  13.    
  14.     body
  15.     {
  16.         width:100%;
  17.         height:100%;
  18.     }
  19.     </style>
  20. </head>
  21. <body>
  22. <script type="text/javascript">
  23. //<![CDATA[
  24.  
  25.     var Video = (function (win, doc) {
  26.  
  27.         return function (opt) {
  28.  
  29.             function init() {
  30.  
  31.                 this.options = {
  32.                     player: null,
  33.  
  34.                     wrap: null,
  35.  
  36.                     id: '',
  37.                     src: '',
  38.                     poster: '',
  39.                     width: 500,
  40.                     height: 344,
  41.                     autoplay: false,
  42.                     controls: false,
  43.                     loop: false,
  44.                     isloaded: false,
  45.                     onload: function(){ ; },
  46.                     onplay: function () { ; },
  47.                     onprogress: function () { ; },
  48.                     ontimeupdate: function() { ; },
  49.                     onended: function () { ; },
  50.                     onerror: function () { ; }
  51.  
  52.                 };
  53.  
  54.                 extend.call(this.options, opt);
  55.  
  56.                 // audio load
  57.                 load.call(this.options);
  58.  
  59.                 return this;
  60.             }
  61.  
  62.             Video.fn = init.prototype = {
  63.                 play: play,
  64.                 stop: stop,
  65.                 isEnded: isEnded,
  66.                 getTimeout: getTimeout,
  67.                 getStartTime: getStartTime,
  68.                 getSrc: getSrc,
  69.                 isBuffering: isBuffering,
  70.                 getCurrentTimeout: getCurrentTimeout,
  71.                 setVolume: setVolume,
  72.                 setMuted: setMuted,
  73.                 getVideoSize: getVideoSize
  74.  
  75.             }
  76.  
  77.             return new init();
  78.         };
  79.  
  80.         // audio 객체를 생성한다.
  81.         function createElement() {
  82.  
  83.             this.player = document.createElement('video');
  84.  
  85.             this.player.id = this.id;
  86.             this.player.src = this.src;
  87.  
  88.             // 미디어 클립이 로드되는 동안 컨텐츠 대신 보여질 이미지 파일의 URL을 지정한다.
  89.             this.player.poster = this.poster;
  90.             // 미디어 클립의 가로폭
  91.             this.player.width = this.width;
  92.             // 미디어 클립의 세로폭
  93.             this.player.height = this.height;
  94.  
  95.             this.player.autoplay = this.autoplay;
  96.             this.player.controls = this.controls;
  97.             this.player.loop = this.loop;
  98.  
  99.             var that = this;
  100.  
  101.             // 미디어클립을 재생할 준비가 완료 시 이벤트 핸들러
  102.             bind(this.player, 'canplay', function () {
  103.  
  104.                 that.onload.call(null);
  105.                 this.isloaded = true;
  106.             });
  107.  
  108.             // 미디어클립 재생 클릭 시 이벤트 핸들러
  109.             bind(this.player, 'play', function () { that.onplay.call(null); });
  110.             // 브라우저가 미디어클립 데이터를 가져오는 프로세스에 있을 시 이벤트 핸들러
  111.             bind(this.player, 'progress', function () { that.onprogress.call(null); });
  112.             // 미디어 클립 재생 시 지속적으로 발생(재생 위치가 변경되었을때)
  113.             bind(this.player, 'timeupdate', function () { that.ontimeupdate.call(null); });
  114.             // 미디어 클립 종료 시 이벤트 핸들러
  115.             bind(this.player, 'ended', function () { that.onended.call(null); });
  116.             // 미디어 클립 로드 오류 시 이벤트 핸들러
  117.             bind(this.player, 'error', function () { that.onerror.call(null); });
  118.  
  119.             return this.player;
  120.         };
  121.  
  122.         // audio 객체를 로드합니다.
  123.         function load() {
  124.            
  125.             var elem = createElement.call(this);
  126.  
  127.             if (elem.load) (this.wrap || document.body).appendChild(elem);
  128.             else alert('Video 객체를 지원하지 않는 브라우저 입니다.');
  129.         };
  130.  
  131.         // 미디어클립을 재생합니다.
  132.         function play() {
  133.  
  134.             this.options.player.play();
  135.  
  136.             return this;
  137.         };
  138.  
  139.         // 미디어클립 재생을 중지합니다.
  140.         function stop() {
  141.  
  142.             !this.options.player.paused && this.options.player.pause();
  143.             return this;
  144.         }
  145.  
  146.         // 미디어클립 재생 여부를 반환
  147.         function isEnded() {
  148.             return this.options.player.ended;
  149.         };
  150.  
  151.  
  152.         // 미디어클립의 총 재생시간을 반환
  153.         function getTimeout(type) {
  154.  
  155.             type = type || 'hours';
  156.  
  157.             return {
  158.                 'second': this.options.player.startTime,
  159.                 'hours': getDateSecondToHours(this.options.player.duration)
  160.             }[type];
  161.         };
  162.  
  163.         // 미디어클립의 현재 재생시간을 반환
  164.         function getCurrentTimeout(type) {
  165.  
  166.             type = type || 'hours';
  167.  
  168.             return {
  169.                 'second': this.options.player.currentTime,
  170.                 'hours': getDateSecondToHours(this.options.player.currentTime)
  171.             }[type];
  172.         };
  173.  
  174.         // 미디어 클립의 현재 재생 시간을 반환
  175.         // 0.0(min) ~ 1(max) 할당한다.
  176.         function setVolume(num) {
  177.  
  178.             num = num || 0;
  179.  
  180.             this.options.player.volume = num / 10;
  181.  
  182.             return this;
  183.         };
  184.  
  185.         // 음소거 여부를 설정한다.
  186.         function setMuted(b) {
  187.  
  188.             b = b || false;
  189.  
  190.             this.options.player.muted = b;
  191.  
  192.             return this;
  193.         };
  194.  
  195.         // 미디어 클립이 재생을 시작할 수 있는 가능한 가장 빠른 시간을 반환합니다.
  196.         // 미디어 클립이 스트리밍되거나, 버퍼링되지 않으면 0을 반환합니다.
  197.         function getStartTime(type) {
  198.  
  199.             return this.options.player.startTime;
  200.         };
  201.  
  202.         // 현재 버퍼링 상태 여부를 반환
  203.         function isBuffering() {
  204.             return this.options.player.startTime !== 0;
  205.         };
  206.  
  207.         // 현재 재생중인 파일명을 반환합니다.
  208.         function getSrc() {
  209.             return this.options.player.currentSrc;
  210.         };
  211.  
  212.         // 미디어클립의 사이즈를 반환한다.
  213.         function getVideoSize() {
  214.             return {
  215.                 w: this.options.player.videoWidth,
  216.                 h: this.options.player.videoHeight
  217.             }
  218.         }
  219.  
  220.  
  221.         function getDateSecondToHours(i) {
  222.  
  223.             i = i || 0;
  224.  
  225.             var h = parseInt(((i / 3600) % 24), 10)
  226.               , m = parseInt(((i / 60) % 60), 10)
  227.               , s = parseInt(((i / 1) % 60), 10);
  228.  
  229.             h = h < 10 ? '0' + h : h;
  230.             m = m < 10 ? '0' + m : m;
  231.             s = s < 10 ? '0' + s : s;
  232.  
  233.             return h + ':' + m + ':' + s;
  234.         };
  235.  
  236.         // 객체 상속 함수
  237.         function extend() {
  238.  
  239.             var target = this
  240.           , opts = []
  241.           , src = null
  242.           , copy = null;
  243.  
  244.             for (var i = 0, length = arguments.length; i < length; i++) {
  245.  
  246.                 opts = arguments[i];
  247.  
  248.                 for (var n in opts) {
  249.                     src = target[n];
  250.                     copy = opts[n];
  251.  
  252.                     if (src === copy) continue;
  253.                     if (copy) target[n] = copy;
  254.                 }
  255.             }
  256.         };
  257.  
  258.  
  259.     })(window, document);
  260.  
  261.  
  262.     bind(window, 'load', function () {
  263.  
  264.         p1 = Video({
  265.             id: 'video_test1',
  266.             src: 'http://m.fpscamp.com/test.mp4',
  267.             poster: 'http://static.naver.net/www/u/2010/0611/nmms_215646753.gif',
  268.             width: document.documentElement.scrollWidth,
  269.             height: window.screen.height,
  270.             autoplay: false,
  271.             controls: true,
  272.             loop: false,
  273.             onload: function () {
  274.             },
  275.             onplay: function () {
  276.             },
  277.             onprogress: function () {
  278.             },
  279.             ontimeupdate: function () {
  280.             },
  281.             onended: function () {
  282.             },
  283.             onerror: function () {
  284.                 alert(this === window);
  285.             }
  286.         });
  287.     });
  288.    
  289.  
  290. // 이벤트 할당
  291. function bind(elem, type, handler, capture) {
  292.     type = typeof type === 'string' && type || '';
  293.     handler = handler || function () { ; };
  294.  
  295.     if (elem.addEventListener) {
  296.         elem.addEventListener(type, handler, capture);
  297.     }
  298.     else if (elem.attachEvent) {
  299.         elem.attachEvent('on' + type, handler);
  300.     }
  301.  
  302.     return elem;
  303. };
  304.  
  305. //]]>
  306. </script>
  307. <input id="" type="button" value="play" onclick="p1.play()" />
  308. <input id="" type="button" value="stop" onclick="p1.stop()" />
  309. <input id="" type="button" value="isEnded" onclick="alert(p1.isEnded())" />
  310. <input id="" type="button" value="getTimeout" onclick="alert(p1.getTimeout())" />
  311. <input id="" type="button" value="getStartTime" onclick="alert(p1.getStartTime())" />
  312. <input id="" type="button" value="getSrc" onclick="alert(p1.getSrc())" />
  313. <input id="" type="button" value="isBuffering" onclick="alert(p1.isBuffering())" />
  314. <input id="" type="button" value="getCurrentTimeout" onclick="alert(p1.getCurrentTimeout())" />
  315. <input id="" type="button" value="setVolume" onclick="p1.setVolume(5)" />
  316. <input id="" type="button" value="setMuted" onclick="p1.setMuted(true)" />
  317. <input id="Button1" type="button" value="getVideoSize(width)" onclick="alert(p1.getVideoSize().w)" />
  318. <input id="Button2" type="button" value="getVideoSize(height)" onclick="alert(p1.getVideoSize().h)" />
  319.  
  320. <div id="test"></div>
  321. </body>
  322. </html>



실행 페이지:





Video 객체 브라우저 지원 여부:





참고사이트:


레퍼런스:

http://www.w3schools.com/html5/tag_video.asp


브라우저 지원 여부

 http://caniuse.com/


@박종명님의 블로그


http://m.mkexdev.net/63



HTML5 API - Audio



총 2회에 걸쳐 HTML5 API의 Audio 객체와 Video 객체에 대해 알아 보도록 하겠습니다.


또한, 글로 기능을 나열하기 보다는 소스 위주의 설명으로 진행하도록 하겠습니다.



아래는 HTML5 API가 지원하고 있는 Audio 객체의 모든 기능을 모듈화 시킨 코드이며, 현재 명세에 있는 모든 기능을 포함합니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Audio</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.     var Audio = (function (win, doc) {
  11.  
  12.         return function (opt) {
  13.  
  14.             function init() {
  15.  
  16.                 this.options = {
  17.                     player: null,
  18.  
  19.                     wrap: null,
  20.  
  21.                     id: '',
  22.                     src: '',
  23.                     autoplay: false,
  24.                     controls: false,
  25.                     loop: false,
  26.                     isloaded: false,
  27.                     onload: function () { ; },
  28.                     onplay: function () { ; },
  29.                     onprogress: function () { ; },
  30.                     ontimeupdate: function () { ; },
  31.                     onended: function () { ; },
  32.                     onerror: function () { ; }
  33.                 };
  34.  
  35.                 extend.call(this.options, opt);
  36.  
  37.                 // audio load
  38.                 load.call(this.options);
  39.  
  40.                 return this;
  41.             }
  42.  
  43.             Audio.fn = init.prototype = {
  44.                 play: play,
  45.                 stop: stop,
  46.                 isEnded: isEnded,
  47.                 getTimeout: getTimeout,
  48.                 getStartTime: getStartTime,
  49.                 getSrc: getSrc,
  50.                 isBuffering: isBuffering,
  51.                 getCurrentTimeout: getCurrentTimeout,
  52.                 setVolume: setVolume,
  53.                 setMuted: setMuted
  54.  
  55.             }
  56.  
  57.             return new init();
  58.         };
  59.  
  60.         // audio 객체를 생성한다.
  61.         function createElement() {
  62.  
  63.             this.player = document.createElement('audio');
  64.  
  65.             this.player.id = this.id;
  66.             this.player.src = this.src;
  67.             this.player.autoplay = this.autoplay;
  68.             this.player.controls = this.controls;
  69.             this.player.loop = this.loop;
  70.  
  71.             // 미디어클립을 재생할 준비가 완료 시 이벤트 핸들러
  72.             bind(this.player, 'canplay', function () {
  73.  
  74.                 that.onload.call(null);
  75.                 this.isloaded = true;
  76.             });
  77.  
  78.             var that = this;
  79.  
  80.             // 미디어클립 재생 클릭 시 이벤트 핸들러
  81.             bind(this.player, 'play', function () { that.onplay.call(null); });
  82.             // 브라우저가 미디어클립 데이터를 가져오는 프로세스에 있을 시 이벤트 핸들러
  83.             bind(this.player, 'progress', function () { that.onprogress.call(null); });
  84.             // 미디어 클립 재생 시 지속적으로 발생(재생 위치가 변경되었을때)
  85.             bind(this.player, 'timeupdate', function () { that.ontimeupdate.call(null); });
  86.             // 미디어 클립 종료 시 이벤트 핸들러
  87.             bind(this.player, 'ended', function () { that.onended.call(null); });
  88.             // 미디어 클립 로드 오류 시 이벤트 핸들러
  89.             bind(this.player, 'error', function () { that.onerror.call(null); });
  90.  
  91.             return this.player;
  92.         };
  93.  
  94.         // audio 객체를 로드합니다.
  95.         function load() {
  96.             var elem = createElement.call(this);
  97.  
  98.             if (elem.load) (this.wrap || document.body).appendChild(elem);
  99.             else alert('Audio 객체를 지원하지 않는 브라우저 입니다.');
  100.         };
  101.  
  102.         // 미디어클립을 재생합니다.
  103.         function play() {
  104.  
  105.             this.options.player.play();
  106.  
  107.             return this;
  108.         };
  109.  
  110.         // 미디어클립 재생을 중지합니다.
  111.         function stop() {
  112.  
  113.             !this.options.player.paused && this.options.player.pause();
  114.             return this;
  115.         }
  116.  
  117.         // 미디어클립 재생 여부를 반환
  118.         function isEnded() {
  119.             return this.options.player.ended;
  120.         };
  121.  
  122.  
  123.         // 미디어클립의 총 재생시간을 반환
  124.         function getTimeout(type) {
  125.  
  126.             type = type || 'hours';
  127.  
  128.             return {
  129.                 'second': this.options.player.startTime,
  130.                 'hours': getDateSecondToHours(this.options.player.duration)
  131.             }[type];
  132.         };
  133.  
  134.         // 미디어클립의 현재 재생시간을 반환
  135.         function getCurrentTimeout(type) {
  136.  
  137.             type = type || 'hours';
  138.  
  139.             return {
  140.                 'second': this.options.player.currentTime,
  141.                 'hours': getDateSecondToHours(this.options.player.currentTime)
  142.             }[type];
  143.         };
  144.  
  145.         // 미디어 클립의 현재 재생 시간을 반환
  146.         // 0.0(min) ~ 1(max) 할당한다.
  147.         function setVolume(num) {
  148.  
  149.             num = num || 0;
  150.  
  151.             this.options.player.volume = num / 10;
  152.  
  153.             return this;
  154.         };
  155.  
  156.         // 음소거 여부를 설정한다.
  157.         function setMuted(b) {
  158.  
  159.             b = b || false;
  160.  
  161.             this.options.player.muted = b;
  162.  
  163.             return this;
  164.         };
  165.  
  166.         // 미디어 클립이 재생을 시작할 수 있는 가능한 가장 빠른 시간을 반환합니다.
  167.         // 미디어 클립이 스트리밍되거나, 버퍼링되지 않으면 0을 반환합니다.
  168.         function getStartTime(type) {
  169.  
  170.             return this.options.player.startTime;
  171.         };
  172.  
  173.         // 현재 버퍼링 상태 여부를 반환
  174.         function isBuffering() {
  175.             return this.options.player.startTime !== 0;
  176.         };
  177.  
  178.         // 현재 재생중인 파일명을 반환합니다.
  179.         function getSrc() {
  180.             return this.options.player.currentSrc;
  181.         };
  182.  
  183.  
  184.         function getDateSecondToHours(i) {
  185.  
  186.             i = i || 0;
  187.  
  188.             var h = parseInt(((i / 3600) % 24), 10)
  189.               , m = parseInt(((i / 60) % 60), 10)
  190.               , s = parseInt(((i / 1) % 60), 10);
  191.  
  192.             h = h < 10 ? '0' + h : h;
  193.             m = m < 10 ? '0' + m : m;
  194.             s = s < 10 ? '0' + s : s;
  195.  
  196.             return h + ':' + m + ':' + s;
  197.         };
  198.  
  199.         // 객체 상속 함수
  200.         function extend() {
  201.  
  202.             var target = this
  203.           , opts = []
  204.           , src = null
  205.           , copy = null;
  206.  
  207.             for (var i = 0, length = arguments.length; i < length; i++) {
  208.  
  209.                 opts = arguments[i];
  210.  
  211.                 for (var n in opts) {
  212.                     src = target[n];
  213.                     copy = opts[n];
  214.  
  215.                     if (src === copy) continue;
  216.                     if (copy) target[n] = copy;
  217.                 }
  218.             }
  219.         };
  220.  
  221.  
  222.     })(window, document);
  223.  
  224.  
  225.     bind(window, 'load', function () {
  226.  
  227.         p1 = Audio({
  228.             id: 'audio_test1',
  229.             src: 'http://m.fpscamp.com/free.mp3',
  230.             autoplay: false,
  231.             controls: true,
  232.             loop: false,
  233.             onload: function () {
  234.             },
  235.             onplay: function () {
  236.             },
  237.             onprogress: function () {
  238.             },
  239.             ontimeupdate: function () {
  240.             },
  241.             onended: function () {
  242.                 alert('onended');
  243.             },
  244.             onerror: function () {
  245.                 alert(this === window);
  246.             }
  247.         });
  248.     });
  249.  
  250.     // 이벤트 할당
  251.     function bind(elem, type, handler, capture) {
  252.         type = typeof type === 'string' && type || '';
  253.         handler = handler || function () { ; };
  254.  
  255.         if (elem.addEventListener) {
  256.             elem.addEventListener(type, handler, capture);
  257.         }
  258.         else if (elem.attachEvent) {
  259.             elem.attachEvent('on' + type, handler);
  260.         }
  261.  
  262.         return elem;
  263.     };
  264.  
  265. //]]>
  266. </script>
  267. <input id="" type="button" value="play" onclick="p1.play()" />
  268. <input id="" type="button" value="stop" onclick="p1.stop()" />
  269. <input id="" type="button" value="isEnded" onclick="alert(p1.isEnded())" />
  270. <input id="" type="button" value="getTimeout" onclick="alert(p1.getTimeout())" />
  271. <input id="" type="button" value="getStartTime" onclick="alert(p1.getStartTime())" />
  272. <input id="" type="button" value="getSrc" onclick="alert(p1.getSrc())" />
  273. <input id="" type="button" value="isBuffering" onclick="alert(p1.isBuffering())" />
  274. <input id="" type="button" value="getCurrentTimeout" onclick="alert(p1.getCurrentTimeout())" />
  275. <input id="" type="button" value="setVolume" onclick="p1.setVolume(5)" />
  276. <input id="" type="button" value="setMuted" onclick="p1.setMuted(true)" />
  277. </body>
  278. </html>



실행 페이지:


Audio 객체 브라우저 지원 상황:




참고사이트:


레퍼런스:

http://www.w3schools.com/html5/tag_audio.asp


브라우저 지원 여부

 http://caniuse.com/


@박종명님의 블로그


http://m.mkexdev.net/63



HTML5 API - Canvas - 2




16. CanvasRenderingContext2D.quadraticCurveTo(cpx, cpy, x, y): 


한 개의 조절점(중심점)(cpx, cpy)을 마지막으로 지정된 현재 좌표와 조절점 그리고 지정된점(x, y)에 인접한 원호를 그린다.


cpx: 호를 그리는 조절점 가로 좌표

cpy: 호를 그리는 조절점 세로 좌표

x: 호가 인접하는 두번째 직선의 종료 가로 좌표

y: 호가 인접하는 두번째 직선의 종료 세로 좌표




  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function quadraticCurveTo() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d');
  13.  
  14.        // rect() 메서드는 이전에 배운 fillRect() 메서드와는 달리 경로가 지정된 도형의 외각선을 그리는 stroke() 메소드를 사용해야한다.
  15.        ctx.beginPath();
  16.  
  17.        ctx.beginPath();
  18.        ctx.moveTo(10, 90);
  19.        ctx.lineTo(100, 10);
  20.        ctx.lineTo(190, 90);
  21.        ctx.strokeStyle = "black";
  22.  
  23.        ctx.closePath();
  24.  
  25.        ctx.stroke();
  26.  
  27.        ctx.beginPath();
  28.        ctx.moveTo(10, 90);
  29.  
  30.        ctx.strokeStyle = 'red';
  31.        ctx.quadraticCurveTo(100, 10, 190, 90);
  32.        
  33.        ctx.stroke();
  34.  
  35.        
  36.    }
  37.  
  38.  
  39.  
  40.    function bind(elem, type, handler, capture) {
  41.        type = typeof type === 'string' && type || '';
  42.        handler = handler || function () { ; };
  43.        capture = capture || false;
  44.  
  45.        if (elem.addEventListener) {
  46.            elem.addEventListener(type, handler, capture);
  47.        }
  48.        else if (elem.attachEvent) {
  49.            elem.attachEvent('on' + type, handler);
  50.        }
  51.  
  52.        return elem;
  53.    };
  54.  
  55.  
  56.    bind(window, 'load', function () {
  57.        quadraticCurveTo();
  58.    });
  59.  
  60.  
  61. //]]>
  62. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  63. </body>
  64. </html>



실행 결과:









17. CanvasRenderingContext2D.bezierCurveTo(cplx, cply, cp2x, cp2y, x, y):


한 개의 조절점(중심점)(cpx, cpy)를 마지막으로 지정된 현재 좌표와 조절점 그리고 지정된점(x, y)에 인접한 원호를 그린다.


cp1x: 베지어 첫번째 조절점 가로 좌표

cp2y: 베지어 첫번째 조절점 세로 좌표

cp1x: 베지어 두번째 조절점 가로 좌표

cp2y: 베지어 두번째 조절점 세로 좌표

x: 베지어 곡선을 그리기 위한 가상 직선 종료 점 가로 좌표

y: 베지어 곡선을 그리기 위한 가상 직선 종료 점 세로 좌표




  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function bezierCurveTo() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d');
  13.  
  14.        ctx.beginPath();
  15.        ctx.moveTo(10, 90);
  16.        ctx.lineTo(40, 10);
  17.        ctx.strokeStyle = "black";
  18.        
  19.        ctx.stroke();
  20.  
  21.        ctx.beginPath();
  22.        ctx.moveTo(150, 10);
  23.        ctx.lineTo(190, 90);
  24.        ctx.strokeStyle = "black";
  25.        
  26.        ctx.stroke();
  27.  
  28.        ctx.beginPath();
  29.        ctx.moveTo(10, 90);
  30.        ctx.bezierCurveTo(40, 10, 150, 10, 190, 90);
  31.        ctx.strokeStyle = "red";
  32.        
  33.        ctx.stroke();
  34.  
  35.        
  36.    }
  37.  
  38.  
  39.  
  40.    function bind(elem, type, handler, capture) {
  41.        type = typeof type === 'string' && type || '';
  42.        handler = handler || function () { ; };
  43.        capture = capture || false;
  44.  
  45.        if (elem.addEventListener) {
  46.            elem.addEventListener(type, handler, capture);
  47.        }
  48.        else if (elem.attachEvent) {
  49.            elem.attachEvent('on' + type, handler);
  50.        }
  51.  
  52.        return elem;
  53.    };
  54.  
  55.  
  56.    bind(window, 'load', function () {
  57.        bezierCurveTo();
  58.    });
  59.  
  60.  
  61. //]]>
  62. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  63. </body>
  64. </html>



실행 결과:







18. CanvasRenderingContext2D.clip(): 경로로 지정된 모든 도형을 클립 영역으로 지정한다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function clip() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.  
  18.  
  19.        bind(img, 'load', function(){
  20.            ctx.drawImage(img, 0, 0, 500, 344);
  21.        });
  22.  
  23.  
  24.        ctx.beginPath();
  25.        
  26.        // 경로로 지정된 모든 도형은 클립 영역 생성이 가능하다.
  27.  
  28.        //ctx.rect(10, 10, 90, 90);
  29.        ctx.arc(100, 100, 100, 0, Math.PI * 2);
  30.        
  31.        //ctx.moveTo(100, 10);
  32.        //ctx.lineTo(10, 100);
  33.        //ctx.lineTo(190, 100);
  34.  
  35.        ctx.closePath();
  36.        ctx.clip();
  37.  
  38.        
  39.    }
  40.  
  41.  
  42.  
  43.    function bind(elem, type, handler, capture) {
  44.        type = typeof type === 'string' && type || '';
  45.        handler = handler || function () { ; };
  46.        capture = capture || false;
  47.  
  48.        if (elem.addEventListener) {
  49.            elem.addEventListener(type, handler, capture);
  50.        }
  51.        else if (elem.attachEvent) {
  52.            elem.attachEvent('on' + type, handler);
  53.        }
  54.  
  55.        return elem;
  56.    };
  57.  
  58.  
  59.    bind(window, 'load', function () {
  60.        clip();
  61.    });
  62.  
  63.  
  64. //]]>
  65. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  66. </body>
  67. </html>



실행 결과:









19.


CancasRenderingContext2D.drawImage(in HTMLImageElement image, in float dx, in float dy): 

CancasRenderingContext2D.drawImage(in HTMLImageElement image, in float dx, in float dy, optional in float dw, in float dh): 

CancasRenderingContext2D.drawImage(in HTMLImageElement image, in float dx, in float dy, optional in float dw, in float dh, in float sx, in float sy, in float sw, in float sh): 


경로로 지정된 이미지 영역을 지정한다.



dx: 이미지가 그려질 위치 가로 좌표

dy: 이미지가 그려질 위치 세로 좌표   

dw: 그려질 이미지의 가로 폭

dh: 그려질 이미지의 세로 폭

sx: 원 이미지에서 그려질 부분의 가로 시작 좌표

sy: 원 이미지에서 그려질 부분의 세로 시작 좌표

sw: 원 이미지에서 그려질 부분의 가로 폭

sh: 원 이미지에서 그려질 부분의 세로 폭


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function drawImage() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.  
  18.  
  19.        bind(img, 'load', function(){
  20.            ctx.drawImage(img, 0, 0);
  21.            ctx.drawImage(img, 0, 0, img.width / 2, img.height / 2);
  22.            ctx.drawImage(img, 0, 0, 100, 100, 100, 0, 40, 40);
  23.        });
  24.    }
  25.  
  26.  
  27.  
  28.    function bind(elem, type, handler, capture) {
  29.        type = typeof type === 'string' && type || '';
  30.        handler = handler || function () { ; };
  31.        capture = capture || false;
  32.  
  33.        if (elem.addEventListener) {
  34.            elem.addEventListener(type, handler, capture);
  35.        }
  36.        else if (elem.attachEvent) {
  37.            elem.attachEvent('on' + type, handler);
  38.        }
  39.  
  40.        return elem;
  41.    };
  42.  
  43.  
  44.    bind(window, 'load', function () {
  45.        drawImage();
  46.    });
  47.  
  48.  
  49. //]]>
  50. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  51. </body>
  52. </html>



실행결과:







20. CancasRenderingContext2D.getImageData(x, y, w, h): context에 생성된 이미지의 픽셀 데이타를 가져온다.

21. CancasRenderingContext2D.putImageData(data, x, y): 픽셀 데이타로 이미지를 생성한다.


x: 이미지가 그려질 위치 가로 좌표

y: 이미지가 그려질 위치 세로 좌표   

w: 그려질 이미지의 가로 폭

h: 그려질 이미지의 세로 폭


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function bezierCurveTo() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.  
  18.  
  19.        bind(img, 'load', function () {
  20.            ctx.drawImage(img, 0, 0, img.width, img.height);
  21.        });
  22.  
  23.        // 이미지 pixel data로 가져온다.
  24.        var pxs = ctx.getImageData(0, 0, img.width, img.height);
  25.        //pixel 배열 정보에 대한 길이
  26.        alert(pxs.data.length); // [255, 0, 0, 255,....]
  27.  
  28.        // 이미지 pixel data로 컨텍스트에 이미지를 생성한다.
  29.        ctx.putImageData(pxs, 0, 0);
  30.  
  31.    }
  32.  
  33.  
  34.  
  35.    function bind(elem, type, handler, capture) {
  36.        type = typeof type === 'string' && type || '';
  37.        handler = handler || function () { ; };
  38.        capture = capture || false;
  39.  
  40.        if (elem.addEventListener) {
  41.            elem.addEventListener(type, handler, capture);
  42.        }
  43.        else if (elem.attachEvent) {
  44.            elem.attachEvent('on' + type, handler);
  45.        }
  46.  
  47.        return elem;
  48.    };
  49.  
  50.  
  51.    bind(window, 'load', function () {
  52.        bezierCurveTo();
  53.    });
  54.  
  55.  
  56. //]]>
  57. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  58. </body>
  59. </html>






22. CanvasRenderingContext2D.translate(in float x, in float y): context의 이동좌표를 지정한다.


x: 이동할 context의 가로 좌표

y: 이동할 context의 세로 좌표   


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function translate() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.  
  18.  
  19.        ctx.save();
  20.        ctx.translate(0, 0);
  21.        ctx.fillStyle = "black";
  22.        ctx.fillRect(0, 0, 50, 50);
  23.        ctx.restore();
  24.  
  25.        ctx.save();
  26.        ctx.translate(50, 0);
  27.        ctx.fillStyle = "red";
  28.        ctx.fillRect(0, 0, 50, 50);
  29.        ctx.restore();
  30.  
  31.        ctx.save();
  32.        ctx.translate(100, 0);
  33.        ctx.fillStyle = "green";
  34.        ctx.fillRect(0, 0, 50, 50);
  35.        ctx.restore();
  36.  
  37.        ctx.save();
  38.        ctx.translate(150, 0);
  39.        ctx.fillStyle = "yellow";
  40.        ctx.fillRect(0, 0, 50, 50);
  41.        ctx.restore();
  42.    }
  43.  
  44.  
  45.  
  46.    function bind(elem, type, handler, capture) {
  47.        type = typeof type === 'string' && type || '';
  48.        handler = handler || function () { ; };
  49.        capture = capture || false;
  50.  
  51.        if (elem.addEventListener) {
  52.            elem.addEventListener(type, handler, capture);
  53.        }
  54.        else if (elem.attachEvent) {
  55.            elem.attachEvent('on' + type, handler);
  56.        }
  57.  
  58.        return elem;
  59.    };
  60.  
  61.  
  62.    bind(window, 'load', function () {
  63.        translate();
  64.    });
  65.  
  66.  
  67. //]]>
  68. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  69. </body>
  70. </html>



실행 결과:






23. CanvasRenderingContext2D.save(): context의 현재 상태를 스택에 저장합니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function save() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.  
  18.        ctx.fillStyle = "black";
  19.        ctx.fillRect(20, 20, 50, 50);
  20.  
  21.        // 현재 context 상태를 스택에 저장합니다.
  22.        ctx.save();
  23.  
  24.        ctx.fillStyle = "red";
  25.  
  26.        ctx.fillRect(100, 0, 50, 50);
  27.  
  28.        // 현재 context 상태를 복원합니다.
  29.        // 이와 같은 경우 초기 context의 fillStyle에 정의된 컬러(black)가 새롭게 생성된 사각영역에 적용됩니다.
  30.        // 이유는 초기 저장된 context의 상태가 ctx.restore() 메소드로 복원됐기 때문입니다.
  31.        ctx.restore();
  32.        //ctx.fillStyle = "white";
  33.        ctx.fillRect(0, 0, 20, 20);
  34.    }
  35.  
  36.  
  37.  
  38.    function bind(elem, type, handler, capture) {
  39.        type = typeof type === 'string' && type || '';
  40.        handler = handler || function () { ; };
  41.        capture = capture || false;
  42.  
  43.        if (elem.addEventListener) {
  44.            elem.addEventListener(type, handler, capture);
  45.        }
  46.        else if (elem.attachEvent) {
  47.            elem.attachEvent('on' + type, handler);
  48.        }
  49.  
  50.        return elem;
  51.    };
  52.  
  53.  
  54.    bind(window, 'load', function () {
  55.        save();
  56.    });
  57.  
  58.  
  59. //]]>
  60. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  61. </body>
  62. </html>



실행결과:





24. CanvasRenderingContext2D.restore(): 스택에 마지막으로 저장된 context의 상태를 복원합니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function save() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.  
  18.        ctx.fillStyle = "black";
  19.        ctx.fillRect(20, 20, 50, 50);
  20.  
  21.        // 현재 context 상태를 스택에 저장합니다.
  22.        ctx.save();
  23.  
  24.        ctx.fillStyle = "red";
  25.  
  26.        ctx.fillRect(100, 0, 50, 50);
  27.  
  28.        // 현재 context 상태를 복원합니다.
  29.        // 이와 같은 경우 초기 context의 fillStyle에 정의된 컬러(black)가 새롭게 생성된 사각영역에 적용됩니다.
  30.        // 이유는 초기 저장된 context의 상태가 ctx.restore() 메소드로 복원됐기 때문입니다.
  31.        ctx.restore();
  32.        //ctx.fillStyle = "white";
  33.        ctx.fillRect(0, 0, 20, 20);
  34.    }
  35.  
  36.  
  37.  
  38.    function bind(elem, type, handler, capture) {
  39.        type = typeof type === 'string' && type || '';
  40.        handler = handler || function () { ; };
  41.        capture = capture || false;
  42.  
  43.        if (elem.addEventListener) {
  44.            elem.addEventListener(type, handler, capture);
  45.        }
  46.        else if (elem.attachEvent) {
  47.            elem.attachEvent('on' + type, handler);
  48.        }
  49.  
  50.        return elem;
  51.    };
  52.  
  53.  
  54.    bind(window, 'load', function () {
  55.        save();
  56.    });
  57.  
  58.  
  59. //]]>
  60. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  61. </body>
  62. </html>



실행결과:





25. CanvasRenderingContext2D.rotate(): 원점을 기준으로 캔퍼스를 회전 시킵니다. 이때 사각영역의 좌표 x, y는 지정하지 않습니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function rotate() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.        ctx.fillStyle = "red";
  18.  
  19.        ctx.translate(100, 100);
  20.        
  21.        ctx.fillRect(0, 0, 10, 50);
  22.        ctx.rotate(Math.PI * 2 / 10);
  23.  
  24.        ctx.fillRect(0, 0, 10, 50);
  25.        ctx.rotate(Math.PI * 2 / 10);
  26.  
  27.        ctx.fillRect(0, 0, 10, 50);
  28.        ctx.rotate(Math.PI * 2 / 10);
  29.  
  30.        ctx.fillRect(0, 0, 10, 50);
  31.        ctx.rotate(Math.PI * 2 / 10);
  32.    }
  33.  
  34.  
  35.  
  36.    function bind(elem, type, handler, capture) {
  37.        type = typeof type === 'string' && type || '';
  38.        handler = handler || function () { ; };
  39.        capture = capture || false;
  40.  
  41.        if (elem.addEventListener) {
  42.            elem.addEventListener(type, handler, capture);
  43.        }
  44.        else if (elem.attachEvent) {
  45.            elem.attachEvent('on' + type, handler);
  46.        }
  47.  
  48.        return elem;
  49.    };
  50.  
  51.  
  52.    bind(window, 'load', function () {
  53.        rotate();
  54.    });
  55.  
  56.  
  57. //]]>
  58. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  59. </body>
  60. </html>



실행결과:





26. CanvasRenderingContext2D.transform(in float m11, in float m12, in float m21, in float m22, in float dx, in float dy): 

캔퍼스에 이전에 적용된 변환 행렬 적용 값을 기준으로 새로운 변형 행렬 값을 설정합니다.




  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function transform() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.        var sin = Math.sin(Math.PI / 6);
  18.        var cos = Math.cos(Math.PI / 6);
  19.  
  20.        ctx.translate(100, 100);
  21.        ctx.fillStyle = "rgb( 200,0,0 )";
  22.        ctx.strokeStyle = "rgb(0,0,0)";
  23.  
  24.        for (var i = 0; i <= 12; i++) {
  25.            ctx.fillRect(0, 0, 30, 30);
  26.            ctx.strokeRect(0, 0, 30, 30);
  27.            ctx.transform(cos, sin, -sin, cos, 0, 0);
  28.        }
  29.    }
  30.  
  31.  
  32.  
  33.    function bind(elem, type, handler, capture) {
  34.        type = typeof type === 'string' && type || '';
  35.        handler = handler || function () { ; };
  36.        capture = capture || false;
  37.  
  38.        if (elem.addEventListener) {
  39.            elem.addEventListener(type, handler, capture);
  40.        }
  41.        else if (elem.attachEvent) {
  42.            elem.attachEvent('on' + type, handler);
  43.        }
  44.  
  45.        return elem;
  46.    };
  47.  
  48.  
  49.    bind(window, 'load', function () {
  50.        transform();
  51.    });
  52.  
  53.  
  54. //]]>
  55. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  56. </body>
  57. </html>



실행결과:






27. CanvasRenderingContext2D.setTransform(in float m11, in float m12, in float m21, in float m22, in float dx, in float dy): 

캔퍼스에 변환 행렬 적용 값을 새로 초기화 하여 설정합니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function setTransform() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.        var sin = Math.sin(Math.PI / 6);
  18.        var cos = Math.cos(Math.PI / 6);
  19.  
  20.        ctx.translate(50, 50);
  21.        ctx.fillStyle = "rgb( 200,0,0 )";
  22.        ctx.strokeStyle = "rgb(0,0,0)";
  23.  
  24.        ctx.fillRect(0, 0, 50, 50);
  25.        ctx.strokeRect(0, 0, 50, 50);
  26.  
  27.        ctx.setTransform(cos, sin, -sin, cos, 0, 0);
  28.  
  29.        ctx.translate(100, 100);
  30.        ctx.fillRect(0, 0, 50, 50);
  31.        ctx.strokeRect(0, 0, 50, 50);
  32.    }
  33.  
  34.  
  35.  
  36.    function bind(elem, type, handler, capture) {
  37.        type = typeof type === 'string' && type || '';
  38.        handler = handler || function () { ; };
  39.        capture = capture || false;
  40.  
  41.        if (elem.addEventListener) {
  42.            elem.addEventListener(type, handler, capture);
  43.        }
  44.        else if (elem.attachEvent) {
  45.            elem.attachEvent('on' + type, handler);
  46.        }
  47.  
  48.        return elem;
  49.    };
  50.  
  51.  
  52.    bind(window, 'load', function () {
  53.        setTransform();
  54.    });
  55.  
  56.  
  57. //]]>
  58. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  59. </body>
  60. </html>



실행결과:





28. CanvasRenderingContext2D.lineWidth: canvas 선의 두께를 지정한다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function lineWidth() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.        // 선의 두께를 정의한다.
  18.        ctx.lineWidth = 12;
  19.        ctx.beginPath();
  20.        ctx.moveTo(100, 100);
  21.        ctx.lineTo(50, 50);
  22.  
  23.        ctx.stroke();
  24.    }
  25.  
  26.  
  27.  
  28.    function bind(elem, type, handler, capture) {
  29.        type = typeof type === 'string' && type || '';
  30.        handler = handler || function () { ; };
  31.        capture = capture || false;
  32.  
  33.        if (elem.addEventListener) {
  34.            elem.addEventListener(type, handler, capture);
  35.        }
  36.        else if (elem.attachEvent) {
  37.            elem.attachEvent('on' + type, handler);
  38.        }
  39.  
  40.        return elem;
  41.    };
  42.  
  43.  
  44.    bind(window, 'load', function () {
  45.        lineWidth();
  46.    });
  47.  
  48.  
  49. //]]>
  50. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  51. </body>
  52. </html>



실행결과:





29. CanvasRenderingContext2D.lineCap: canvas 선의 끝 모양을 지정한다.


butt: 아무런 효과가 없다

round: 선 폭의 1/2을 반지름으로 하는 반원이 선 양쪽 끝에 그려진다.

square: 선 폭의 1/2 높이로 하는 사각형이 손 양쪽 끝에 그려진다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function lineCap() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.        // 선의 두께를 정의한다.
  18.        ctx.lineWidth = 12;
  19.        ctx.lineCap = 'round';
  20.        ctx.beginPath();
  21.        ctx.moveTo(100, 100);
  22.        ctx.lineTo(50, 50);
  23.  
  24.        ctx.stroke();
  25.    }
  26.  
  27.  
  28.  
  29.    function bind(elem, type, handler, capture) {
  30.        type = typeof type === 'string' && type || '';
  31.        handler = handler || function () { ; };
  32.        capture = capture || false;
  33.  
  34.        if (elem.addEventListener) {
  35.            elem.addEventListener(type, handler, capture);
  36.        }
  37.        else if (elem.attachEvent) {
  38.            elem.attachEvent('on' + type, handler);
  39.        }
  40.  
  41.        return elem;
  42.    };
  43.  
  44.  
  45.    bind(window, 'load', function () {
  46.        lineCap();
  47.    });
  48.  
  49.  
  50. //]]>
  51. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  52. </body>
  53. </html>



실행결과:





30. CanvasRenderingContext2D.lineJoin: canvas 선과 선의 연결 부분의 모양을 지정한다.


round: 둥근 모양으로 연결된다.

bavel: 연결된 부분이 단면으로 남는다.

miter: 연결한 흔적이 남지 않는다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function lineJoin() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.        // 선의 두께를 정의한다.
  18.        ctx.lineWidth = 12;
  19.        ctx.lineJoin = 'round';
  20.        ctx.beginPath();
  21.        ctx.moveTo(100, 100);
  22.        ctx.lineTo(100, 50);
  23.        ctx.lineTo(150, 100);
  24.  
  25.        ctx.stroke();
  26.    }
  27.  
  28.  
  29.  
  30.    function bind(elem, type, handler, capture) {
  31.        type = typeof type === 'string' && type || '';
  32.        handler = handler || function () { ; };
  33.        capture = capture || false;
  34.  
  35.        if (elem.addEventListener) {
  36.            elem.addEventListener(type, handler, capture);
  37.        }
  38.        else if (elem.attachEvent) {
  39.            elem.attachEvent('on' + type, handler);
  40.        }
  41.  
  42.        return elem;
  43.    };
  44.  
  45.  
  46.    bind(window, 'load', function () {
  47.        lineJoin();
  48.    });
  49.  
  50.  
  51. //]]>
  52. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  53. </body>
  54. </html>



실행결과:





31. CanvasRenderingContext2D.miterLimit: canvas lineJoin 속성이 'miter' 지정되었을 경우 연결선 돌출 부위의 절단 범위를 지정한다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.  
  9.    function miterLimit() {
  10.  
  11.        var cvs = document.getElementById('canvas_test')
  12.          , ctx = cvs.getContext('2d')
  13.          , img = new Image();
  14.  
  15.        //img.src = 'http://movie.phinf.naver.net/20120314_145/1331716835803KBqTp_JPEG/movie_image.jpg?type=m210';
  16.  
  17.        // 선의 두께를 정의한다.
  18.        ctx.lineWidth = 10;
  19.        ctx.lineJoin = 'miter';
  20.        ctx.miterLimit = 1;
  21.  
  22.        ctx.beginPath();
  23.        ctx.moveTo(100, 100);
  24.        ctx.lineTo(100, 50);
  25.        ctx.lineTo(150, 100);
  26.        ctx.stroke();
  27.    }
  28.  
  29.  
  30.  
  31.    function bind(elem, type, handler, capture) {
  32.        type = typeof type === 'string' && type || '';
  33.        handler = handler || function () { ; };
  34.        capture = capture || false;
  35.  
  36.        if (elem.addEventListener) {
  37.            elem.addEventListener(type, handler, capture);
  38.        }
  39.        else if (elem.attachEvent) {
  40.            elem.attachEvent('on' + type, handler);
  41.        }
  42.  
  43.        return elem;
  44.    };
  45.  
  46.  
  47.    bind(window, 'load', function () {
  48.        miterLimit();
  49.    });
  50.  
  51.  
  52. //]]>
  53. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  54. </body>
  55. </html>



실행결과:





32. CanvasRenderingContext2D.createPattern: canvas 경로에 선을 그리거나 색을 채울 때 이미지의 반복 패턴을 정의한다.


반복패턴:


repeat: 양방향으로 이미지가 반복된다.

repeat-x: 가로 방향으로 이미지가 반복된다.

repeat-y: 세로 방향으로 이미지가 반복된다.

no-repeat: 이미지가 반복시키지 않는다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.    function createPattern() {
  9.  
  10.        var cvs = document.getElementById('canvas_test')
  11.          , ctx = cvs.getContext('2d')
  12.          , img = new Image();
  13.  
  14.        img.src = 'http://go.microsoft.com/fwlink/?LinkID=199028';
  15.  
  16.        bind(img, 'load', function () {
  17.        });
  18.  
  19.        var ptn = ctx.createPattern(img, 'repeat');
  20.        ctx.fillStyle = ptn;
  21.        ctx.fillRect(0, 0, 200, 200);
  22.    }
  23.  
  24.    function bind(elem, type, handler, capture) {
  25.  
  26.        type = typeof type === 'string' && type || '';
  27.        handler = handler || function () { ; };
  28.        capture = capture || false;
  29.  
  30.        if (elem.addEventListener) {
  31.            elem.addEventListener(type, handler, capture);
  32.        }
  33.        else if (elem.attachEvent) {
  34.            elem.attachEvent('on' + type, handler);
  35.        }
  36.  
  37.        return elem;
  38.    };
  39.  
  40.  
  41.    bind(window, 'load', function () {
  42.        createPattern();
  43.    });
  44.  
  45.  
  46. //]]>
  47. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  48. </body>
  49. </html>



실행결과:





33. CanvasRenderingContext2D.font:

34. CanvasRenderingContext2D.textAlign:

35. CanvasRenderingContext2D.textBaseLine:


36. CanvasRenderingContext2D.fillText: canvas context에 text를 사용한다.


text: 양방향으로 이미지가 반복된다.

width: 가로 방향으로 이미지가 반복된다.

height: 세로 방향으로 이미지가 반복된다.

max-width: 가로 최대 폭

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.    function fillText() {
  9.  
  10.        var cvs = document.getElementById('canvas_test')
  11.          , ctx = cvs.getContext('2d')
  12.          , img = new Image();
  13.  
  14.        img.src = 'http://go.microsoft.com/fwlink/?LinkID=199028';
  15.  
  16.        // 폰트, 사이즈 지정
  17.        ctx.font = '30px impact';
  18.        // 정렬 지정
  19.        ctx.textAlign = 'center';
  20.        // 포지션 지정
  21.        ctx.textBaseLine = 'top';
  22.  
  23.        ctx.fillText('hello world', 100, 100, 200);
  24.    }
  25.  
  26.    function bind(elem, type, handler, capture) {
  27.  
  28.        type = typeof type === 'string' && type || '';
  29.        handler = handler || function () { ; };
  30.        capture = capture || false;
  31.  
  32.        if (elem.addEventListener) {
  33.            elem.addEventListener(type, handler, capture);
  34.        }
  35.        else if (elem.attachEvent) {
  36.            elem.attachEvent('on' + type, handler);
  37.        }
  38.  
  39.        return elem;
  40.    };
  41.  
  42.  
  43.    bind(window, 'load', function () {
  44.        fillText();
  45.    });
  46.  
  47.  
  48. //]]>
  49. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  50. </body>
  51. </html>



실행결과:






37. CanvasRenderingContext2D.shadowColor: 

38. CanvasRenderingContext2D.shadowOffsetX: 

49. CanvasRenderingContext2D.shadowOffsetY: 

40. CanvasRenderingContext2D.shadowBlur: 


canvas context에 그림자 효과를 사용한다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <title>Canvas</title>
  4. </head>
  5. <script type="text/javascript">
  6. //<![CDATA[
  7.  
  8.    function shadow() {
  9.  
  10.        var cvs = document.getElementById('canvas_test')
  11.          , ctx = cvs.getContext('2d')
  12.          , img = new Image();
  13.  
  14.        img.src = 'http://go.microsoft.com/fwlink/?LinkID=199028';
  15.  
  16.        ctx.font = '30px impact';
  17.        ctx.textAlign = 'center';
  18.        ctx.textBaseLine = 'top';
  19.  
  20.        //그림자 적용
  21.        ctx.shadowColor = 'black';
  22.        ctx.shadowOffsetX = 8;
  23.        ctx.shadowOffsetY = 8;
  24.  
  25.        ctx.shadowBlur = 2;
  26.  
  27.        ctx.fillText('hello world', 100, 100, 200);
  28.    }
  29.  
  30.    function bind(elem, type, handler, capture) {
  31.  
  32.        type = typeof type === 'string' && type || '';
  33.        handler = handler || function () { ; };
  34.        capture = capture || false;
  35.  
  36.        if (elem.addEventListener) {
  37.            elem.addEventListener(type, handler, capture);
  38.        }
  39.        else if (elem.attachEvent) {
  40.            elem.attachEvent('on' + type, handler);
  41.        }
  42.  
  43.        return elem;
  44.    };
  45.  
  46.  
  47.    bind(window, 'load', function () { shadow(); });
  48.  
  49. //]]>
  50. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  51. </body>
  52. </html>



실행결과:









레퍼런스 참조사이트:


http://forum.falinux.com/zbxe/?_filter=search&mid=lecture_tip&category=&search_target=title&search_keyword=canvas



캔버스 레퍼런스 PPT:


http://www.google.co.kr/url?sa=t&rct=j&q=&esrc=s&frm=1&source=web&cd=5&ved=0CGgQFjAE&url=http%3A%2F%2Fss.textcube.com%2Fblog%2F6%2F63442%2Fattach%2FXc03LsAIk0.ppt%2FHTML5%2520%2526%2520API%2520%25EC%259E%2585%25EB%25AC%25B8(1%25EC%25B0%25A8).ppt&ei=S86oT_fNF8qZiAfGiqnPAw&usg=AFQjCNG_UOVjapQMoUS7sX39WugyfZNP5Q&sig2=ae7GLYQ-say_0u9Riun9vQ




HTML5 API - Canvas - 1


HTML5 API 기술 중 가장 많은 설명과 예제가 필요한 기능을 하나 꼽으라면 단연 이번 시간에 설명하려는 Canvas API를 꼽을 수 있을 것입니다. 


그만큼 장기간의 학습 시간이 필요한 기술이며, 기존 플래쉬와 같은 그래픽 프로그램에 익숙하지 않은 개발자는 더 욱 오랜 시간에 걸쳐 학습해야 하기 때문입니다.(저 역시도 그래픽과 관련된 프로그램을 전문적으로 다루고 있지 않아 상황 별 좋은 소스를 보여드리긴 힘들꺼 같습니다.ㅠㅠ;;;)



아래는 API에 대한 설명과 관련 예제를 정리한 내용입니다.





1. HTMLCanvasElement.getContext(id): canvas context객체를 생성한다.


id: 반환 될 컨텍스트 객체를 구별하는 아이디 문자열('2d', '3d(현재 미지원)')


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.     function getContext() {
  11.  
  12.         var cvs = document.getElementById('canvas_test')
  13.           , ctx = cvs.getContext('2d');
  14.  
  15.  
  16.         ctx.beginPath();
  17.         ctx.rect(10, 10, 85, 85);
  18.  
  19.         ctx.rect(105, 10, 85, 85);
  20.         ctx.stroke();
  21.     }
  22.  
  23.  
  24.  
  25.     function bind(elem, type, handler, capture) {
  26.         type = typeof type === 'string' && type || '';
  27.         handler = handler || function () { ; };
  28.         capture = capture || false;
  29.  
  30.         if (elem.addEventListener) {
  31.             elem.addEventListener(type, handler, capture);
  32.         }
  33.         else if (elem.attachEvent) {
  34.             elem.attachEvent('on' + type, handler);
  35.         }
  36.  
  37.         return elem;
  38.     };
  39.  
  40.  
  41.     bind(window, 'load', function () {
  42.         getContext();
  43.     });
  44.  
  45.  
  46. //]]>
  47. </script>
  48. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  49. </body>
  50. </html>




실행결과:








2. CanvasRenderingContext2D.fillStyle: 경로(Path)를 통해 그려지는 도형 내부에 채워지는 스타일을 지정한다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function fillStyle() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.  
  16.         ctx.beginPath();
  17.         ctx.moveTo(10, 10);
  18.         ctx.lineTo(90, 10);
  19.         ctx.lineTo(90, 90);
  20.         ctx.closePath();
  21.  
  22.         // 스타일 지정
  23.         ctx.fillStyle = 'red';
  24.        
  25.         ctx.fill();
  26.         ctx.stroke();
  27.     }
  28.  
  29.  
  30.  
  31.     function bind(elem, type, handler, capture) {
  32.         type = typeof type === 'string' && type || '';
  33.         handler = handler || function () { ; };
  34.         capture = capture || false;
  35.  
  36.         if (elem.addEventListener) {
  37.             elem.addEventListener(type, handler, capture);
  38.         }
  39.         else if (elem.attachEvent) {
  40.             elem.attachEvent('on' + type, handler);
  41.         }
  42.  
  43.         return elem;
  44.     };
  45.  
  46.  
  47.     bind(window, 'load', function () {
  48.         fillStyle();
  49.     });
  50.  
  51.  
  52. //]]>
  53. </script>
  54. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  55. </body>
  56. </html>




실행결과:








3. CanvasRenderingContext2D.fillRect(x, y, w, h): 사각영역에 색을 칠한다.


x: 영역의 왼쪽 위 가로 좌표

y: 영역의 왼쪽 위 세로 좌표

w: 가로 사이즈

h: 세로 사이즈


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function fillRect() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.  
  16.         // 스타일 지정
  17.         ctx.fillStyle = 'red';
  18.         ctx.fillRect(10, 10, 90, 90);
  19.     }
  20.  
  21.  
  22.  
  23.     function bind(elem, type, handler, capture) {
  24.         type = typeof type === 'string' && type || '';
  25.         handler = handler || function () { ; };
  26.         capture = capture || false;
  27.  
  28.         if (elem.addEventListener) {
  29.             elem.addEventListener(type, handler, capture);
  30.         }
  31.         else if (elem.attachEvent) {
  32.             elem.attachEvent('on' + type, handler);
  33.         }
  34.  
  35.         return elem;
  36.     };
  37.  
  38.  
  39.     bind(window, 'load', function () {
  40.         fillStyle();
  41.     });
  42.  
  43.  
  44. //]]>
  45. </script>
  46. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  47. </body>
  48. </html>




실행결과







4. CanvasRenderingContext2D.clearRect(x, y, w, h): 사각영역을 배경으로 채워 삭제된 효과를 준다.


x: 영역의 왼쪽 위 가로 좌표

y: 영역의 왼쪽 위 세로 좌표

w: 가로 사이즈

h: 세로 사이즈


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function clearRect() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.  
  16.         // 스타일 지정
  17.         ctx.fillStyle = 'red';
  18.         ctx.fillRect(10, 10, 90, 90);
  19.        
  20.         // 클리어
  21.         ctx.clearRect(15, 15, 80, 80);
  22.     }
  23.  
  24.  
  25.  
  26.     function bind(elem, type, handler, capture) {
  27.         type = typeof type === 'string' && type || '';
  28.         handler = handler || function () { ; };
  29.         capture = capture || false;
  30.  
  31.         if (elem.addEventListener) {
  32.             elem.addEventListener(type, handler, capture);
  33.         }
  34.         else if (elem.attachEvent) {
  35.             elem.attachEvent('on' + type, handler);
  36.         }
  37.  
  38.         return elem;
  39.     };
  40.  
  41.  
  42.     bind(window, 'load', function () {
  43.         clearRect();
  44.     });
  45.  
  46.  
  47. //]]>
  48. </script>
  49. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  50. </body>
  51. </html>




실행결과:







5. CanvasRenderingContext2D.strokeRect(x, y, w, h): 사각영역의 테두리를 그린다.


x: 영역의 왼쪽 위 가로 좌표

y: 영역의 왼쪽 위 세로 좌표

w: 가로 사이즈

h: 세로 사이즈


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function strokeRect() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.  
  16.         ctx.strokeRect(10, 10, 90, 90);
  17.     }
  18.  
  19.  
  20.  
  21.     function bind(elem, type, handler, capture) {
  22.         type = typeof type === 'string' && type || '';
  23.         handler = handler || function () { ; };
  24.         capture = capture || false;
  25.  
  26.         if (elem.addEventListener) {
  27.             elem.addEventListener(type, handler, capture);
  28.         }
  29.         else if (elem.attachEvent) {
  30.             elem.attachEvent('on' + type, handler);
  31.         }
  32.  
  33.         return elem;
  34.     };
  35.  
  36.  
  37.     bind(window, 'load', function () {
  38.         strokeRect();
  39.     });
  40.  
  41.  
  42. //]]>
  43. </script>
  44. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  45. </body>
  46. </html>




실행결과:







6. CanvasRenderingContext2D.strokeStyle: 테두리 스타일을 지정한다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function strokeStyle() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.        
  16.         // 스타일 지정
  17.         ctx.strokeStyle = 'red';
  18.  
  19.         ctx.strokeRect(10, 10, 90, 90);
  20.     }
  21.  
  22.  
  23.  
  24.     function bind(elem, type, handler, capture) {
  25.         type = typeof type === 'string' && type || '';
  26.         handler = handler || function () { ; };
  27.         capture = capture || false;
  28.  
  29.         if (elem.addEventListener) {
  30.             elem.addEventListener(type, handler, capture);
  31.         }
  32.         else if (elem.attachEvent) {
  33.             elem.attachEvent('on' + type, handler);
  34.         }
  35.  
  36.         return elem;
  37.     };
  38.  
  39.  
  40.     bind(window, 'load', function () {
  41.         strokeStyle();
  42.     });
  43.  
  44.  
  45. //]]>
  46. </script>
  47. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  48. </body>
  49. </html>




실행결과:







7. CanvasRenderingContext2D.beginPath(): 그리는 경로의 시작에 반드시 붙어준다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function beginPath() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.        
  16.         // 경로에 시작을 알려준다.
  17.         ctx.beginPath();
  18.  
  19.         ctx.moveTo(10, 10);
  20.         ctx.lineTo(90, 10);
  21.  
  22.         ctx.stroke();
  23.  
  24.         // 경로에 마지막을 알려준다.
  25.         ctx.closePath();
  26.  
  27.  
  28.         // 새롭게 경로를 시작한다.
  29.         ctx.beginPath();
  30.  
  31.         ctx.moveTo(190, 10);
  32.         ctx.lineTo(100, 10);
  33.         ctx.stroke();
  34.  
  35.         ctx.closePath();
  36.     }
  37.  
  38.  
  39.  
  40.     function bind(elem, type, handler, capture) {
  41.         type = typeof type === 'string' && type || '';
  42.         handler = handler || function () { ; };
  43.         capture = capture || false;
  44.  
  45.         if (elem.addEventListener) {
  46.             elem.addEventListener(type, handler, capture);
  47.         }
  48.         else if (elem.attachEvent) {
  49.             elem.attachEvent('on' + type, handler);
  50.         }
  51.  
  52.         return elem;
  53.     };
  54.  
  55.  
  56.     bind(window, 'load', function () {
  57.         beginPath();
  58.     });
  59.  
  60.  
  61. //]]>
  62. </script>
  63. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  64. </body>
  65. </html>




실행결과:








8. CanvasRenderingContext2D.closePath(): 


1. 그리는 경로를 종료한다.

2. 마지막 지점에서 시작점까지 직선을 그린다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function closePath() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.        
  16.         // 경로에 시작을 알려준다.
  17.         ctx.beginPath();
  18.  
  19.         ctx.moveTo(10, 10);
  20.         ctx.lineTo(90, 10);
  21.         ctx.lineTo(10, 90);
  22.  
  23.         // 마지막 지점에서 시작점까지 직선을 그린다.
  24.         ctx.closePath();
  25.  
  26.         ctx.stroke();
  27.        
  28.     }
  29.  
  30.  
  31.  
  32.     function bind(elem, type, handler, capture) {
  33.         type = typeof type === 'string' && type || '';
  34.         handler = handler || function () { ; };
  35.         capture = capture || false;
  36.  
  37.         if (elem.addEventListener) {
  38.             elem.addEventListener(type, handler, capture);
  39.         }
  40.         else if (elem.attachEvent) {
  41.             elem.attachEvent('on' + type, handler);
  42.         }
  43.  
  44.         return elem;
  45.     };
  46.  
  47.  
  48.     bind(window, 'load', function () {
  49.         closePath();
  50.     });
  51.  
  52.  
  53. //]]>
  54. </script>
  55. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  56. </body>
  57. </html>




실행결과







9. CanvasRenderingContext2D.moveTo(x, y): 시작 포인트를 이동 시킨다.


x: 시작점의 가로 좌표

y: 시작점의 세로 좌표


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function moveTo() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.        
  16.         // 경로에 시작을 알려준다.
  17.         ctx.beginPath();
  18.  
  19.         ctx.moveTo(10, 10);
  20.         ctx.moveTo(20, 20);
  21.  
  22.         // 최종 시작점은 x: 30, y: 30 좌표 지점에서 시작된다.
  23.         ctx.moveTo(30, 30);
  24.  
  25.         ctx.lineTo(90, 30);
  26.  
  27.         // 마지막 지점에서 시작점까지 직선을 그린다.
  28.         ctx.closePath();
  29.  
  30.         ctx.stroke();
  31.        
  32.     }
  33.  
  34.  
  35.  
  36.     function bind(elem, type, handler, capture) {
  37.         type = typeof type === 'string' && type || '';
  38.         handler = handler || function () { ; };
  39.         capture = capture || false;
  40.  
  41.         if (elem.addEventListener) {
  42.             elem.addEventListener(type, handler, capture);
  43.         }
  44.         else if (elem.attachEvent) {
  45.             elem.attachEvent('on' + type, handler);
  46.         }
  47.  
  48.         return elem;
  49.     };
  50.  
  51.  
  52.     bind(window, 'load', function () {
  53.         moveTo();
  54.     });
  55.  
  56.  
  57. //]]>
  58. </script>
  59. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  60. </body>
  61. </html>




실행결과:







10. CanvasRenderingContext2D.lineTo(x, y): 시작점부터 x, y 위치까지 직선을 그린다.


x: 직선의 종료 가로 좌표

y: 직선의 종료 세로 좌표


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function lineTo() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.        
  16.         ctx.beginPath();
  17.  
  18.         ctx.moveTo(10, 10);
  19.         ctx.moveTo(20, 20);
  20.  
  21.         ctx.moveTo(30, 30);
  22.  
  23.         // 시작점부터 x, y 위치까지 직선을 그린다.
  24.         ctx.lineTo(90, 30);
  25.  
  26.         ctx.closePath();
  27.  
  28.         ctx.stroke();
  29.        
  30.     }
  31.  
  32.  
  33.  
  34.     function bind(elem, type, handler, capture) {
  35.         type = typeof type === 'string' && type || '';
  36.         handler = handler || function () { ; };
  37.         capture = capture || false;
  38.  
  39.         if (elem.addEventListener) {
  40.             elem.addEventListener(type, handler, capture);
  41.         }
  42.         else if (elem.attachEvent) {
  43.             elem.attachEvent('on' + type, handler);
  44.         }
  45.  
  46.         return elem;
  47.     };
  48.  
  49.  
  50.     bind(window, 'load', function () {
  51.         lineTo();
  52.     });
  53.  
  54.  
  55. //]]>
  56. </script>
  57. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  58. </body>
  59. </html>




실행결과:








11. CanvasRenderingContext2D.rect(x, y, w, h): 경로가 지정된 사각형을 그린다.


x: 사각 영역의 왼쪽 위 가로 좌표

y: 사각 영역의 왼쪽 위 세로 좌표

w: 사각 영역의 가로 폭

h: 사각 영역의 세로 폭


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function rect() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.  
  16.         // rect() 메서드는 이전에 배운 fillRect() 메서드와는 달리 경로가 지정된 도형의 외각선을 그리는 stroke() 메소드를 사용해야한다.
  17.         ctx.beginPath();
  18.  
  19.         ctx.rect(10, 10, 90, 90);
  20.         ctx.stroke();
  21.  
  22.         ctx.closePath();
  23.     }
  24.  
  25.  
  26.  
  27.     function bind(elem, type, handler, capture) {
  28.         type = typeof type === 'string' && type || '';
  29.         handler = handler || function () { ; };
  30.         capture = capture || false;
  31.  
  32.         if (elem.addEventListener) {
  33.             elem.addEventListener(type, handler, capture);
  34.         }
  35.         else if (elem.attachEvent) {
  36.             elem.attachEvent('on' + type, handler);
  37.         }
  38.  
  39.         return elem;
  40.     };
  41.  
  42.  
  43.     bind(window, 'load', function () {
  44.         rect();
  45.     });
  46.  
  47.  
  48. //]]>
  49. </script>
  50. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  51. </body>
  52. </html>




실행결과:







12. CanvasRenderingContext2D.arc(x, y, radius, startAngle, endAngle, anticlockwise): 원이나 호를 그린다.


x: 호가 시작되는 가로 좌표

y: 호가 시작되는 세로 좌표

radius : 호의 반지름

startAngle: 호의 시작 각도 라디안(radian) 단위

endAngle: 호의 종료 각도 라디안(radian) 단위

anticlockwise: 호를 그리는 반향이 반시계 반향 일 때 true



  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function arc() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.  
  16.  
  17.         ctx.beginPath();
  18.  
  19.         ctx.arc(40, 120, 40, 0, (Math.PI / 180) * -90, false);
  20.         ctx.stroke();
  21.  
  22.         ctx.closePath();
  23.        
  24.         ctx.beginPath();
  25.  
  26.         ctx.arc(40, 40, 40, (Math.PI / 180) * 90, 0, false);
  27.         ctx.stroke();
  28.  
  29.         ctx.closePath();
  30.  
  31.         // 원둘레
  32.         ctx.beginPath();
  33.  
  34.         ctx.arc(40, 160, 40, 0, (Math.PI * 2), false);
  35.         ctx.stroke();
  36.  
  37.         ctx.closePath();
  38.     }
  39.  
  40.  
  41.  
  42.     function bind(elem, type, handler, capture) {
  43.         type = typeof type === 'string' && type || '';
  44.         handler = handler || function () { ; };
  45.         capture = capture || false;
  46.  
  47.         if (elem.addEventListener) {
  48.             elem.addEventListener(type, handler, capture);
  49.         }
  50.         else if (elem.attachEvent) {
  51.             elem.attachEvent('on' + type, handler);
  52.         }
  53.  
  54.         return elem;
  55.     };
  56.  
  57.  
  58.     bind(window, 'load', function () {
  59.         arc();
  60.     });
  61.  
  62.  
  63. //]]>
  64. </script>
  65. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  66. </body>
  67. </html>




실행결과:








13. CanvasRenderingContext2D.arcTo(x1, y1, x2, y2, radius): 두 개의 접점을 연결하는 원호를 그린다.


마지막으로 지정된  현재 좌표(x0,y0)에서 (x1, y1)을 연결하는 직선, 그리고 (x1, y1)과 (x2, y2)를 연결하는 가상의 직선에 동시에 접하는 반지름(radius)의 가상의 원을 기준으로 호를 그린다.


x1: 호가 인접하는 첫번째 직선의 종료 가로 좌표

y1: 호가 인접하는 첫번째 직선의 종료 세로 좌표

x2: 호가 인접하는 두번째 직선의 종료 가로 좌표

y2: 호가 인접하는 두번째 직선의 종료 세로 좌표

radius : 호의 반지름



  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function arcTo() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.  
  16.        
  17.         // 원둘레
  18.         ctx.beginPath();
  19.         ctx.moveTo(100, 0);
  20.         ctx.arcTo(200, 0, 200, 200, 100);
  21.        
  22.         //ctx.closePath();
  23.         ctx.strokeStyle = 'red';
  24.         ctx.stroke();
  25.  
  26.        
  27.     }
  28.  
  29.  
  30.  
  31.     function bind(elem, type, handler, capture) {
  32.         type = typeof type === 'string' && type || '';
  33.         handler = handler || function () { ; };
  34.         capture = capture || false;
  35.  
  36.         if (elem.addEventListener) {
  37.             elem.addEventListener(type, handler, capture);
  38.         }
  39.         else if (elem.attachEvent) {
  40.             elem.attachEvent('on' + type, handler);
  41.         }
  42.  
  43.         return elem;
  44.     };
  45.  
  46.  
  47.     bind(window, 'load', function () {
  48.         arcTo();
  49.     });
  50.  
  51.  
  52. //]]>
  53. </script>
  54. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  55. </body>
  56. </html>




실행결과:









14. CanvasRenderingContext2D.stroke(): 경로에 지정된 외각선을 그린다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function stroke() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.  
  16.        
  17.         // 원둘레
  18.         ctx.beginPath();
  19.         ctx.moveTo(100, 0);
  20.         ctx.arcTo(200, 0, 200, 200, 100);
  21.        
  22.         //ctx.closePath();
  23.         ctx.strokeStyle = 'red';
  24.  
  25.         // 외각선을 그린다.
  26.         ctx.stroke();
  27.  
  28.        
  29.     }
  30.  
  31.  
  32.  
  33.     function bind(elem, type, handler, capture) {
  34.         type = typeof type === 'string' && type || '';
  35.         handler = handler || function () { ; };
  36.         capture = capture || false;
  37.  
  38.         if (elem.addEventListener) {
  39.             elem.addEventListener(type, handler, capture);
  40.         }
  41.         else if (elem.attachEvent) {
  42.             elem.attachEvent('on' + type, handler);
  43.         }
  44.  
  45.         return elem;
  46.     };
  47.  
  48.  
  49.     bind(window, 'load', function () {
  50.         stroke();
  51.     });
  52.  
  53.  
  54. //]]>
  55. </script>
  56. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  57. </body>
  58. </html>




실행결과:







15. CanvasRenderingContext2D.fill(): 경로에 지정된 도형의 색을 채운다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Canvas</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.  
  11.     function fill() {
  12.  
  13.         var cvs = document.getElementById('canvas_test')
  14.           , ctx = cvs.getContext('2d');
  15.  
  16.         // rect() 메서드는 이전에 배운 fillRect() 메서드와는 달리 경로가 지정된 도형의 외각선을 그리는 stroke() 메소드를 사용해야한다.
  17.         ctx.beginPath();
  18.  
  19.         ctx.rect(10, 10, 90, 90);
  20.        
  21.         ctx.fillStyle = 'red';
  22.         ctx.fill();
  23.  
  24.         ctx.strokeStyle = 'green';
  25.         ctx.stroke();
  26.        
  27.         ctx.closePath();
  28.  
  29.        
  30.     }
  31.  
  32.  
  33.  
  34.     function bind(elem, type, handler, capture) {
  35.         type = typeof type === 'string' && type || '';
  36.         handler = handler || function () { ; };
  37.         capture = capture || false;
  38.  
  39.         if (elem.addEventListener) {
  40.             elem.addEventListener(type, handler, capture);
  41.         }
  42.         else if (elem.attachEvent) {
  43.             elem.attachEvent('on' + type, handler);
  44.         }
  45.  
  46.         return elem;
  47.     };
  48.  
  49.  
  50.     bind(window, 'load', function () {
  51.         fill();
  52.     });
  53.  
  54.  
  55. //]]>
  56. </script>
  57. <canvas id="canvas_test" width="200" height="200" style="border:black 1px solid"></canvas>
  58. </body>
  59. </html>




실행결과:












레퍼런스 참조사이트:


http://forum.falinux.com/zbxe/?_filter=search&mid=lecture_tip&category=&search_target=title&search_keyword=canvas







prev 1 2 next