HTML Canvas - strokeRect() 方法



HTML Canvas 的strokeRect() 方法是 Canvas 2D API 的一部分,可用於使用引數提供的資料繪製矩形的邊框。

它在CanvasRenderingContext2D介面中可用,如果沒有指定顏色,則會將畫布元素的指定區域邊框繪製為黑色。

在繪製矩形之前,我們可以使用上下文物件的strokeStyle屬性來指定顏色。應明確定義此屬性,以避免任何導致方法無法正常工作的錯誤。

呼叫此方法時,傳入的座標被視為矩形左上角的座標,邊框將使用給定的輸入(預設為黑色)進行繪製。

語法

以下是 HTML Canvas strokeRect() 方法的語法:

CanvasRenderingContext2D.strokeRect(x, y, width, height);

引數

以下是此方法的引數列表:

.
序號 引數及描述
1x

矩形起始點的 x 座標值。

2 y

矩形起始點的 y 座標值。

3 width

繪製矩形的寬度。

4 height

繪製矩形的高度。

返回值

呼叫此方法時,將根據傳遞給方法的引數繪製矩形的邊框。

示例

以下程式碼使用 HTML Canvas strokeRect() 方法建立一個使用預設顏色樣式的矩形邊框。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body onload="Context();">
      <canvas id="canvas" width="350" height="250" style="border: 1px solid black;"></canvas>
      <script>
         function Context() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            context.strokeRect(50, 50, 200, 150);
         }
      </script>
   </body>
</html>

輸出

以上程式碼在網頁中返回的輸出如下:

HTML Canvas StrokeRect Method

示例

以下示例使用為上下文物件指定的strokeStyle屬性中指定的值為矩形新增邊框。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body onload="Context();">
      <canvas id="canvas" width="350" height="250" style="border: 1px solid black;"></canvas>
      <script>
         function Context() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            context.strokeStyle = 'green';
            context.lineWidth = 3;
            context.strokeRect(50, 50, 200, 150);
         }
      </script>
   </body>
</html>

輸出

以上程式碼在網頁中返回的輸出如下:

HTML Canvas StrokeRect Method

示例

以下示例使用strokeStyle屬性中指定的值為矩形新增邊框,並使用其他“線條”屬性透過上下文物件繪製設計的矩形。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body onload="Context();">
      <canvas id="canvas" width="350" height="250" style="border: 1px solid black;"></canvas>
      <script>
         function Context() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            context.strokeStyle = 'purple';
            context.lineWidth = 10;
            context.shadowColor = 'orange';
            context.shadowBlur = 15;
            context.strokeRect(25, 25, 250, 200)
         }
      </script>
   </body>undefined
</html>

輸出

以上程式碼在網頁中返回的輸出如下:

HTML Canvas StrokeRect Method
html_canvas_rectangles.htm
廣告
© . All rights reserved.