HTML Canvas - stroke() 方法



HTML Canvas 的 stroke() 方法用于在给定路径或任何形状的轮廓上添加描边。

它默认使用黑色为路径添加描边,并且还会搜索由 strokeStyle 属性给定的输入颜色,并使用此颜色输入代替黑色。

语法

以下是 HTML Canvas stroke() 方法的语法:

CanvasRenderingContext2D.stroke(path);

参数

以下是此方法使用的参数:

序号 参数及说明
1 path

用于应用 stroke() 方法的路径。

返回值

应用了 stroke() 方法的路径,在 Canvas 元素内使用黑色进行描边。如果存在 strokeStyle 属性,则使用其中传递的颜色对路径进行描边。

示例 1

以下示例使用 HTML Canvas stroke() 方法在 Canvas 元素上为矩形添加描边。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.rect(25, 25, 150, 100);
      context.stroke();
   </script>
</body>
</html>

输出

上述代码在网页上返回的输出如下:

HTML Canvas Stroke Method

示例 2

以下示例首先创建一个空路径,并使用 lineTo() 方法绘制一个三角形,然后使用 stroke() 方法和 strokeStyle 属性中指定的颜色为 Canvas 元素添加描边。

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

输出

上述代码在网页上返回的输出如下:

HTML Canvas Stroke Method
html_canvas_paths.htm
广告

© . All rights reserved.