效果圖:
代碼:
1 <canvas id="c1" width="400" height="400" style="background-color:red"> 2 </canvas> 3 4 <script type="text/javascript"> 5 //獲取畫布元素 6 var canvas=document.getElementById("c1"); 7 //繪制環境(我稱為“畫筆”) 8 var cxt=canvas.getContext("2d"); 9 10 //畫一個實體方塊---fillRect(x,y,w,h); 11 cxt.fillRect(50,50,100,100); 12 13 //畫出一個空心方塊---strokeRect(x,y,w,h); 14 cxt.strokeRect(200,200,100,100); 15 //cxt.strokeRect(200.5,200.5,100,100); 16 </script>
【知識點】:fill(填充)、stroke(畫線)
1、fillRect(x,y,w,h); //繪制實體方塊,默認黑色
2、strokeRect(x,y,w,h); //繪制空心方塊
3、x,y:為起始坐標點 w,h:為寬和高的值
【需要注意的地方】:
cxt.strokeRect(200,200,100,100);
效果圖: 這里它占了兩個像素,是因為該點在200像素的線上,線兩邊一邊0.5像素,系統自動補全了另一半。
cxt.strokeRect(200.5,200.5,100,100);
效果圖: 默認是一像素的寬