HTML <canvas> Tag with the rect() Method

<canvas id="myCanvas" width="350" height="630">
<p>Fallback content for browsers that don't support the canvas tag.</p> 
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Using rect() with stroke()
ctx.beginPath();
ctx.rect(5, 5, 180, 100);
ctx.stroke();

// Using rect() with fill()
ctx.beginPath();
ctx.rect(5, 120, 180, 100);
ctx.fill();

// Using rect() with fill() & fillStyle
ctx.beginPath();
ctx.fillStyle = 'Orange';
ctx.rect(5, 240, 180, 100);
ctx.fill();

// Create gradient
var myGradient = ctx.createLinearGradient(0,0,170,0);
myGradient.addColorStop(0,"LightYellow");
myGradient.addColorStop(1,"Orange");

// Fill with gradient
ctx.beginPath();
ctx.fillStyle = myGradient;
ctx.rect(5,360,180,100);
ctx.fill();
</script>

Fallback content for browsers that don't support the canvas tag.

The above rectangles are drawn using the HTML <canvas> element in conjunction with the rect() method.

The rect() method is used when working with paths. It adds a new closed subpath to the path, representing the given rectangle.

In contrast to fillRect() and strokRect(), which paint a rectangle directly to the canvas, the rect() method doesn't actually paint the rectangle directly to the canvas. It simply adds the new subpath to the current path. The rectangle isn't painted to the canvas until either the fill() or stroke() methods are called.

The rect() method accepts four parameters: rect(x,y,w,h).

x
Horizontal coordinates that the rectangle should start at. This is the number of pixels in from the left.
y
Vertical coordinates that the rectangle should start at. This is the number of pixels in from the top.
w
Width of the rectangle.
h
Height of the rectangle.

Styles

The rect() method paints the given rectangle onto the canvas, using the current fill style. The default color is #000000 (black), so your rectangle will be black if a fill style hasn't yet been specified.

In the above example, the first two rectangles are black because this is the default color (and we didn't specify a fillStyle). The third rectangle is orange because we specified the color with fillStyle. The fourth rectangle uses a gradient because we created a gradient, then applied that gradient to the rectangle using fillStyle.

The beginPath() Method

The beginPath() method resets the current path. In the above example, we use beginPath() to reset the current path so that we can apply different styles to the different rectangles. If we didn't do this, all rectangles would use the fillStyle that was specified last (the gradient).

Also see fillRect() and/or strokeRect() for painting a rectangle directly to the canvas.