1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>HTML5之Canvas畫正方形</title> 6 7 <script type="text/javascript"> 8 function drawFour(id) 9 { 10 //獲取canvas元素 11 12 var canvas=document.getElementById("canvas"); 13 if(canvas == null) 14 return false; 15 //獲取上下文 16 var context = canvas.getContext('2d'); 17 //設定填充圖形的樣式 18 context.fillStyle = "#EEEEFF"; 19 //繪制圖形 20 context.fillRect(0,0,800,800); 21 context.fillStyle = "yellow"; 22 //設定圖形邊框的樣式 23 context.strokeStyle = "blue"; 24 //指定線寬 25 context.lineWidth = 150; 26 context.fillRect(50,50,500,500); 27 context.strokeRect(50,50,500,500); 28 } 29 </script> 30 </head> 31 <body onLoad="drawFour('canvas')"> 32 33 34 35 <canvas id="canvas" width="1200" height="560" /> 36 37 </body> 38 39 40 </html>
分析說明:
(1)獲取Canvas元素
var canvas =
document.getElementById("canvas");
(2)取到上下文
var context = canvas.getContext('2d');
(3)填充繪制邊框
context.fillStyle = "#EEEEFF";//填充的樣式
(4)設定繪圖樣式
strokeStyle:圖形邊框的樣式
(5)指定線寬
context.lineWidth = 150;
(6)指定顏色值
(7)繪制正方形
context.fillRect(50,50,500,500);
context.strokeRect(50,50,500,500);
效果圖:

