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.