位置:首頁 > 軟件操作教程 > 編程開發(fā) > HTML > 問題詳情

HTML5 繪制矩形與三角形

提問人:劉團(tuán)圓發(fā)布時(shí)間:2020-11-14

【例題】利用canvas繪制矩形

    canvas只是一個(gè)繪制圖形的容器,除了id、class、style等屬性外,還有height和width屬性。在canvas元素上繪圖主要有三步:

1.獲取canvas元素對應(yīng)的DOM對象,這是一個(gè)Canvas對象。

2.調(diào)用Canvas對象的getContext()方法,得到—個(gè)CanvasRenderingContext2D對象。

3.調(diào)用CanvasRende「ingContext2D對象進(jìn)行繪圖。

    繪制矩形rect()、fillRect()和strokeRect():

    ? context.rect( x,y,width,height ):只定義矩形的路徑。

    ? context.fillRect( x,y,width,height):直接繪制出填充的矩形。

    ? context.strokeRect( x,y,width,height )直接繪制出矩形邊框。


HTML代碼如下:

<canvas id="demo" width="300" height="300"></canvas>


JavaScript代碼如下:

<script>

Var canvas=document.getElementById ("demo");

Var context=canvas.getContext("2d");

//使用rect方法

context.rect(10,10,190,190); 

context.lineWidth = 2; 

context.fillStyle = "#3EE4CB";

context.strokeStyle ="#F527OB";

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.flllRect(610,10,190,190);

</script〉

繼續(xù)查找其他問題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部