HTML <canvas> Tag with the fillRect() Method

<canvas id="myCanvas" width="350" height="530">
<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");

// Default fill
ctx.fillRect (5, 5, 170, 120);

// GreenYellow fill
ctx.fillStyle = "GreenYellow";
ctx.fillRect (5, 170, 170, 120);

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

// Fill with gradient
ctx.fillStyle = myGradient;
ctx.fillRect(5,335,170,120);
</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 fillRect() method.

The fillRect() method accepts four parameters: fillRect(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 fillRect() 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 rectangle is black because this is the default color (and we didn't specify a fillStyle). The second rectangle is GreenYellow because we specified the color with fillStyle. The third rectangle uses a gradient because we created a gradient, then applied that gradient to the rectangle using fillStyle.

You can also use strokeStyle along with the strokeRect() method to create a rectangle outline.