Open In App

HTML canvas strokeRect() Method

Last Updated : 09 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The strokeRect() method is used to draw the rectangle in a given color. The default color of the stroke is black. 

Syntax:

context.strokeRect(x, y, width, height)

Parameters:

  • x: It stores the x-coordinate of the top-left corner of the rectangle.
  • y: It stores the y-coordinate of the top-left corner of the rectangle.
  • width: It stores the width in pixels.
  • height: It stores the height in pixels.

Example 1: 

html




<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML canvas strokeRect() Method
    </title>
</head>
  
<body>
    <canvas id="GFG"
            width="500" 
            height="300">
  </canvas>
  
    <script>
        var x =
            document.getElementById("GFG");
        var context = x.getContext("2d");
        context.strokeRect(50, 50, 350, 200);
        context.stroke();
    </script>
  
</body>
  
</html>


Output: 

Example 2: 

html




<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML canvas 
      strokeRect() Method
    </title>
</head>
  
<body>
    <canvas id="GFG" 
            width="500"
            height="300">
  </canvas>
  
    <script>
        var x =
            document.getElementById("GFG");
        var context =
            x.getContext("2d");
        context.strokeStyle = "green";
        context.strokeRect(50, 50, 350, 200);
  
        context.strokeStyle = "red";
        context.strokeRect(100, 100, 250, 100);
        context.stroke();
    </script>
  
</body>
  
</html>


Output: 

Supported Browsers:

  • Google Chrome
  • Internet Explorer 9.0
  • Firefox
  • Safari
  • Opera


Previous Article
Next Article