Skip to main content
rect method

Creates a new closed rectangular subpath.

HTML Canvas 2D Context, Section 9 Internet Explorer 9

Syntax

var retval = CanvasRenderingContext2D.rect(x, y, w, h);

Parameters

x [in]

Type: Floating-point

The x-coordinate, in pixels, of the upper-left corner of the rectangle in relation to the coordinates of the canvas.

y [in]

Type: Floating-point

The y-coordinate, in pixels, of the upper-left corner of the rectangle in relation to the coordinates of the canvas.

w [in]

Type: Floating-point

The width, in pixels, of the rectangle in relation to the coordinates of the canvas.

h [in]

Type: Floating-point

The height, in pixels, of the rectangle in relation to the coordinates of the canvas.

Return value

Type: HRESULT

If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

Standards information

Remarks

The rect method creates a closed path for the rectangle and then starts a new subpath at the point (x, y). You can fill the rectangle by using the fillStyle property and the fill method.

Examples

The following code example creates three rectangles by using the rect method. The example uses the beginPath method between creating each rectangle to use different colors and styles.


<html>
<head>
  <title>Rect example</title>
  <script type="text/javascript">
      function draw() {
          var canvas = document.getElementById("MyCanvas");
          //  if canvas is supported, get context and draw three rects
          if (canvas.getContext) {
              var ctx = canvas.getContext("2d");
              ctx.beginPath();
              ctx.lineWidth = "3";
              ctx.strokeStyle = "blue";
              ctx.rect(5, 5, 300, 250);
              ctx.stroke();
              ctx.beginPath();
              ctx.lineWidth = "5";
              ctx.strokeStyle = "red";
              ctx.rect(150, 200, 300, 150);
              ctx.stroke();
              ctx.beginPath();
              ctx.lineJoin = "round";
              ctx.lineWidth = "10";
              ctx.strokeStyle = "green";
              ctx.rect(250, 50, 150, 250);
              ctx.stroke();
          }
      }
  </script>
</head>
<body onload="draw();">
  <canvas id="MyCanvas" width="600" height="600">This browser or document mode doesn't support canvas</canvas> 
</body>
</html>

See also

CanvasRenderingContext2D

 

 

Send comments about this topic to Microsoft

Build date: 11/28/2012