【HTML 5】HTML5 Canvas rect(), strokeRect() 和 fillRect() 的區別


 

他們都接受相同的參數,見頁面表格。唯一不同的實現方式與效果方面有差異。

其中fillRect()與strokeRect() 在調用后會立即在畫布上畫面效果,而rect()不會立即將圖形畫出,只有在調用了stroke()方法之后,才會實際作用於畫布。

 

fillRect()

 

從字面上很好理解fillRect()與其他兩個的區別,它是執行填充操作。填充一個矩形區域。

下面是來自W3SHOOL中文站點對它的具體參數及API的詳解:

定義和用法

fillRect() 方法繪制"已填色"的矩形。默認的填充顏色是黑色。

 

參數

x

矩形左上角的 x

y

矩形左上角的 y

width

矩形的寬度,以像素

height

矩形的高度,以像素

 

strokeRect()

 

strokeRect() 方法繪制矩形(不填色)。筆觸的默認顏色是黑色。

下面看一下strokeRect() 與fillRect()的例子。

 

 

<html>

<head>

<title>HTML 5 Canvas rect</title>

</head>

<body>

<canvas id="c" width="400" height="300"></canvas>

</body>

<script type="text/javascript">

var c = document.getElementById('c');

var ctx = c.getContext('2d');

 

// draw rectangle via strokeRect() method

ctx.strokeRect(0, 0, 100, 100);

 

// draw rectangle via fillRect() method

ctx.fillRect(101, 0, 100, 100);

</script>

</html>

 

 

效果:

 

rect()

 

rect() 方法創建矩形。但它並不會真正將矩形畫出,只能調用stroke() 或 fill()后才會真正作用於畫布。

下面的例子將展示這一特性。

<html>

<head>

<title>HTML 5 Canvas rect</title>

</head>

<body>

<canvas id="c" width="400" height="300"></canvas>

</body>

<script type="text/javascript">

var c = document.getElementById('c');

var ctx = c.getContext('2d');

 

// draw rectangle via strokeRect() method

ctx.rect(0, 0, 100, 100);

 

//set time out, the rectngle will be drawed out after 5 secs.

setTimeout(function () { ctx.stroke() }, 5000)

</script>

</html>

 

 

雖然執行了rect(),但只有5秒后執行了stroke()后,畫布上才會出現矩形圖案。

 

 

參考:

http://www.rgraph.net/blog/2013/january/the-difference-between-rect-strokerect-and-fillrect.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM