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