HTML canvas rect() 方法


HTML canvas 的 rect() 方法用於建立矩形。<canvas> 元素允許您使用 JavaScript 在網頁上繪製圖形。每個 canvas 都有兩個元素來描述 canvas 的高和寬,即 height 和 width。

語法如下 −

context.fillRect(p,q,width,height);

上述中,

  • p: 矩形左上角的 x 座標
  • q: 矩形左上角的 y 座標
  • width: 矩形的寬度
  • height: 矩形的高度

現在我們來看一個示例來實現 canvas 的 rect() 方法 −

示例

 線上演示

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="450" height="350" style="border:2px solid blue;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
   var c = document.getElementById("myCanvas");
   var ctx = c.getContext("2d");
   ctx.beginPath();
   ctx.rect(100, 60, 200, 200);
   ctx.fillStyle = "orange";
   ctx.fill();
   ctx.beginPath();
   ctx.rect(110, 90, 180, 120);
   ctx.fillStyle = "yellow";
   ctx.fill();
</script>
</body>
</html>

輸出

更新日期:2019 年 7 月 30 日

327 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告