HTML 5 快速導覽 - 內嵌元素 <canvas>

<canvas> 為 HTML 文件的內嵌元素 (element) ,用來繪製圖形或製作動畫。



<canvas> 除了全域屬性外,另有定義幾個屬性 (attribute)
  • width
  • height


此外, <canvas> 的文件物件模型 (DOM) 介面為 HTMLCanvasElement ,另有定義屬性與方法如下
  • width
  • height
  • toDataURL()
  • toBlob()
  • getContext()


繪製圖形或製作動畫便是利用 getContext() 回傳的 CanvasRenderingContext2D 物件,然後以 JavaScript 程式設計繪製路徑或動畫進行模式。舉例如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<!DOCTYPE html> 
<html
  <head
     <title>HTML 5 DEMO</title>
     <style>
       header, nav, section, article, footer {
         display: block;
       }
       header, nav, section, article, footer {
         color: white;
       }
       header, footer {
         text-align: center;
         width: 100%;
       }
       header {
         background-color: red;
         font-size: 36px;
         font-weight: bold;
       }
       nav {
         position: fixed;
         top: 40px;
         right: 25px;
         background-color: blue;
         width: 100px;
       }
       section {
         width: 86%;
         background-color: gray;
         padding: 20px;
         margin: 20px;
       }
       footer {
         background-color: green;
         font-size: 10px;
       }
     </style>
     <script>
       function run() {
         var d = document.getElementsByTagName("canvas");
         var c = d[0].getContext("2d");
         c.fillStyle = "rgb(100, 100, 100)"; 
         c.fillRect(10, 10, 160, 160); 
         c.fillStyle = "rgb(0, 0, 0)"; 
         c.fillRect(30, 30, 120, 120);
       }
     </script>
  </head
  <body onload="run();"
    <header
       header 
    </header
    <nav
      <ul>
        <li>nav 1</li>
        <li>nav 2</li>
      </ul
    </nav>
    <section>
      <article>
        <canvas id="demo" width="180" height="180">
      </article>
    </section>     
    <footer
      <p>
        footer © 2011
      </p>      
    </footer
  </body
</html
 
<!-- 《程式語言教學誌》的範例程式
     檔名:canvastest.html
     功能:示範 HTML 5 標記語言
     作者:張凱慶
     時間:西元 2011 年 12 月 -->


此例, <track> 放在 <video> 中
60
61
62
63
64
<section>
  <article>
    <canvas id="demo" width="180" height="180">
  </article>
</section>


利用 Firefox 開啟如下



中英文術語對照
元素element
屬性attribute
文件物件模型DOM


您可以繼續參考
JavaScript 範例

內嵌元素


相關目錄
HTML 5 快速導覽
HTML, CSS 教材
首頁


參考資料
http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element
http://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html#the-canvas-element

1 則留言:

Long Lasting 提到...

Well Written Beautiful Post!
here is my post related to html canvas.
you may like.
Convert HTML to Canvas