標籤: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-基礎知識