Skip to main content
fillRect method

Paints a rectangle onto a CanvasRenderingContext2D object by using the current fill style.

HTML Canvas 2D Context, Section 8 Internet Explorer 9

Syntax

CanvasRenderingContext2D.fillRect(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

This method does not return a value.

Standards information

Remarks

If the w or h parameter is zero, the fillRect method does not draw the rectangle.

Examples

The following code example fills rectangles by using a linear gradient and a solid color.


<!DOCTYPE html> <html>
<head>
  <script type="text/javascript">
function draw()
{
  var canvas = document.getElementById("MyCanvas");
    if (canvas.getContext) {
      //get a context       
      var ctx = canvas.getContext("2d");
      //create a gradient object
      var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
      // Add the colors with fixed stops at 1/4 of the width.
      gradient.addColorStop("0","magenta");
      gradient.addColorStop(".25","blue");
      gradient.addColorStop(".50","green");
      gradient.addColorStop(".75","yellow");
      gradient.addColorStop("1.0","red");      
      // Use the gradient as a fill pattern
      ctx.fillStyle = gradient;
      ctx.fillRect (0,0,300,250);  
      ctx.fillStyle = "blue";
      ctx.fillRect(250,300,600,500);
    }  
}
  </script>
</head>
<body onload="draw();">
  <canvas id="MyCanvas" width="600" height="500"> </canvas> 
</body>
</html>

See also

CanvasRenderingContext2D
strokeRect
fillStyle

 

 

Send comments about this topic to Microsoft

Build date: 11/28/2012