<canvas></canvas>是HTML5中新增的標簽,用于繪制圖形,這篇文章主要為大家詳細介紹了HTML5 canvas基本繪圖之繪制矩形方法,感興趣的小伙伴們可以參考一下
<canvas></canvas>只是一個繪制圖形的容器,除了id、class、style等屬性外,還有height和width屬性。在<canvas>>元素上繪圖主要有三步:
1.獲取<canvas>元素對應的DOM對象,這是一個Canvas對象;
2.調用Canvas對象的getContext()方法,得到一個CanvasRenderingContext2D對象;
3.調用CanvasRenderingContext2D對象進行繪圖。
繪制矩形rect()、fillRect()和strokeRect()
?context.rect( x , y , width , height ):只定義矩形的路徑;
?context.fillRect( x , y , width , height ):直接繪制出填充的矩形;
?context.strokeRect( x , y , width , height ):直接繪制出矩形邊框;
JavaScript Code復制內容到剪貼板
-
<script type="text/javascript">
-
var canvas = document.getElementById("canvas");
-
var context = canvas.getContext("2d");
-
//使用rect方法
-
context.rect(10,10,190,190);
-
context.lineWidth = 2;
-
context.fillStyle = "#3EE4CB";
-
context.strokeStyle = "#F5270B";
-
context.fill();
-
context.stroke();
-
//使用fillRect方法
-
context.fillStyle = "#1424DE";
-
context.fillRect(210,10,190,190);
-
//使用strokeRect方法
-
context.strokeStyle = "#F5270B";
-
context.strokeRect(410,10,190,190);
-
//同時使用strokeRect方法和fillRect方法
-
context.fillStyle = "#1424DE";
-
context.strokeStyle = "#F5270B";
-
context.strokeRect(610,10,190,190);
-
context.fillRect(610,10,190,190);
-
</script>
這里需要說明兩點:第一點就是stroke()和fill()繪制的前后順序,如果fill()后面繪制,那么當stroke邊框較大時,會明顯的把stroke()繪制出的邊框遮住一半;第二點:設置fillStyle或strokeStyle屬性時,可以通過“rgba(255,0,0,0.2)”的設置方式來設置,這個設置的最后一個參數是透明度。
另外還有一個跟矩形繪制有關的:清除矩形區域:context.clearRect(x,y,width,height)。
接收參數分別為:清除矩形的起始位置以及矩形的寬和長。
在上面的代碼中繪制圖形的最后加上:
context.clearRect(100,60,600,100);
可以得到以下效果: