HTML Canvas - setLineDash() 方法



HTML Canvas 的setLineDash() 方法用於在需要繪製 Canvas 元素中的線條時設定線段圖案。

它接受一個數組,該陣列指定長度和間隙值,並應用樣式。它在CanvasRenderingContext2D 介面中可用。

語法

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

CanvasRenderingContext2D.setLineDash(values); 

引數

以下是此方法使用的引數:

序號 引數及說明
1 values

一個數字陣列,表示保持每條線段之間的間距以及線段圖案長度的距離。

返回值

只有當使用相應的方法描邊或填充時,才會在畫布元素上返回線段圖案。

示例

以下示例使用 HTML Canvas setLineDash() 方法為CanvasRenderingContext2D 物件繪製虛線。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="200" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.setLineDash([4, 16]);
      context.beginPath();
      context.strokeStyle = 'blue';
      context.moveTo(25, 25);
      context.lineTo(125, 25);
      context.lineTo(125, 125);
      context.stroke();
   </script>
</body>
</html>

輸出

以上程式碼在網頁上返回的輸出為:

HTML Canvas SetLineDash Method

示例

以下示例在 Canvas 上繪製一個正方形,並將其邊框應用setLineDash() 方法以獲得線段圖案。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="200" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.beginPath();
      context.lineWidth = 10;
      context.strokeStyle = 'black';
      context.moveTo(25, 25);
      context.lineTo(25, 125);
      context.lineTo(125, 125);
      context.stroke();
      context.closePath();
      context.setLineDash([4, 16]);
      context.beginPath();
      context.lineWidth = 1;
      context.strokeStyle = 'blue';
      context.moveTo(25, 25);
      context.lineTo(125, 25);
      context.lineTo(125, 125);
      context.stroke();
      context.closePath();
   </script>
</body>
</html>

輸出

以上程式碼在網頁上返回的輸出為:

HTML Canvas SetLineDash Method
html_canvas_lines.htm
廣告
© . All rights reserved.