HTML Canvas - stroke() Method



The HTML Canvas stroke() method is used to add strokes to the outlines of the given path or any shape.

It adds strokes to the path using black color by default and also searches for the input color given by strokeStyle property and uses this color input instead of black color.

Syntax

Following is the syntax of HTML Canvas stroke() method −

CanvasRenderingContext2D.stroke(path);

Parameters

Following is the parameter used by this method −

S.No Parameters and Description
1 path

Path to be used to apply the stroke() method.

Return Value

The path to which the method stroke() is applied, is stroked inside the Canvas element using black color. If there is strokeStyle property, the color passed there is used to stroke the path.

Example 1

The following example adds strokes to a rectangle on the Canvas element using HTML Canvas stroke() method.

<!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>

Output

The output returned by the above code on the webpage as −

HTML Canvas Stroke Method

Example 2

The following example first creates an empty path and draws a triangle using lineTo() method and later adds strokes to the canvas element using the stroke() method with mentioned color using strokeStyle property.

<!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>

Output

The output returned by the above code on the webpage as −

HTML Canvas Stroke Method
html_canvas_paths.htm
Advertisements