Canvas入門01-基礎知識

來源:互聯網
上載者:User

標籤:fill   影響   上下文   getc   pad   corn   aaa   col   上下   

        定義一個canvas,直接在Html中使用canvas便簽即可。

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6     <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7     <title>Document</title> 8     <style> 9      body {10          background: #ddd;11      }12      #canvas {13          margin: 10px;14          padding: 10px;15          background: #fff;16          border: thin inset #aaa;17      }18     </style>19 </head>20 <body>21     <canvas id="canvas" width="600" height="300">22         Canvas not supported23     </canvas>24     <script src="./example.js"></script>25 </body>26 </html>

  canvas 元素內容部分所含的文本,僅在瀏覽器不支援canvas 元素的時候,才會顯示該內容。這種文本叫做“後備內容”(fallback content)。

        使用canvas畫圖:

1 var canvas = document.getElementById(‘canvas‘);2 var context = canvas.getContext(‘2d‘);3 4 context.font = ‘38pt Arial‘;5 context.fillStyle = ‘cornflowerblue‘;6 context.strokeStyle = ‘blue‘;7 context.fillText(‘Hello Canvas‘, canvas.width/2 - 150, canvas.height/2 + 15);8 context.strokeText(‘Hello Canvas‘, canvas.width/2 - 150, canvas.height/2 + 15);
 

        顯示效果如下:  

 

        使用CSS設定 canvas 的大小和設定 canvas 的屬性有什麼區別?

        canvas 元素實際上有兩套尺寸。一個是元素本身的大小,還有一個是元素繪圖表面(drawing surface)的大小。

當設定元素的 width 和 height 屬性時,實際上是同時修改了元素本身的大小和元素繪圖表面的大小。如果是通過CSS 設定,只會改變元素本身的大小,而不會影響繪圖表面,還是預設的 300 * 150 px,這會影響座標軸的計算。

        小結:

        (1)使用 document.getElementById() 來擷取指向 canvas的引用

        (2)在 canvas 對象上調用 getContext(‘2d‘) 來擷取繪圖上下文(也叫繪圖環境變數),d 必須小寫

        (3)使用 context 對象在 canvas 元素上進行繪製。

        (4)在canvas 元素上設定 width 和 height 屬性來設定 canvas 的 size,預設的 canvas 元素大小是 300*150 px

 

Canvas入門01-基礎知識

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.