HTML Canvas - strokeStyle Property



The HTML Canvas strokeStyle property of Canvas 2D API is from the interface CanvasRenderingContext2D uses the context object of the Canvas element and colors the stroked graphic with the provided color.

It mainly specifies the color, gradient, or pattern for adding strokes to any shape. The color is 'black' by default.

Possible input values

The property accepts any one of the following values −

  • Any format of CSS color value.

  • A gradient object for adding inside the shape.

  • A pattern object for creating a repeated pattern inside the shape.

Example

The following example adds strokes to a rectangle created by the CanvasRenderingContext2D object using color name passed by the HTML Canvas 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="250" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById("canvas");
         var context = canvas.getContext('2d');
         context.strokeStyle = 'grey';
         context.rect(20, 20, 250, 200);
         context.stroke();
      </script>
   </body>
</html>

Output

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

HTML Canvas StrokeStyle Property

Example

The following example adds strokes to a rectangle created by the CanvasRenderingContext2D object using RGB color value.

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

Output

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

HTML Canvas StrokeStyle Property
html_canvas_rectangles.htm
Advertisements