Categories
Web development

HTML Canvas Rectangle

HTML canvas rectangle

The HTML canvas rect() method draws a rectangle.

Syntax:

context.rect(x,y,width,height);

x – the x-coordinate of the upper-left corner of the rectangle.

y – the y-coordinate of the upper-left corner of the rectangle.

width – the width of the rectangle (px).

height – the height of the rectangle (px).

The HTML canvas strokeRect() method creates a rectangle (no fill).

Syntax:

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

x – the x-coordinate of the upper-left corner of the rectangle.

y – the y-coordinate of the upper-left corner of the rectangle.

width – the width of the rectangle (px).

height – the height of the rectangle (px).

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="rectangle" width="200" height="200" style="border:1px solid #333;"></canvas>

<script>
var c = document.getElementById("rectangle");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(50, 50, 100, 100);
ctx.stroke();
</script> 

</body>
</html>

Output:


Note: The default color of the stroke is black. Use the HTML canvas strokeStyle property to define a color, gradient, or pattern to style the stroke.

The HTML canvas fillRect() method creates a “filled” rectangle.

Syntax:

context.fillRect(x,y,width,height);

x – the x-coordinate of the upper-left corner of the rectangle.

y – the y-coordinate of the upper-left corner of the rectangle.

width – the width of the rectangle (px).

height – the height of the rectangle (px).

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="rectangleFill" width="200" height="200" style="border:1px solid #333;"></canvas>

<script>
var c = document.getElementById("rectangleFill");
var ctx = c.getContext("2d");
ctx.fillRect(50, 50, 100, 100);
</script>

</body>
</html>

Output:


Note: The default color of the fill is black. Use the HTML canvas fillStyle property to define a color, gradient, or pattern used to fill the drawing.

The HTML canvas clearRect() method clears the defined pixels within a given rectangle.

Syntax:

context.clearRect(x,y,width,height);

x – the x-coordinate of the upper-left corner of the rectangle.

y – the y-coordinate of the upper-left corner of the rectangle.

width – the width of the rectangle (px).

height – the height of the rectangle (px).

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="200" style="border:1px solid #333;"></canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#2a9d8f";
ctx.fillRect(0, 0, 200, 200);
ctx.clearRect(50, 50, 100, 100);
</script>

</body>
</html>

Output:


Enjoy coding!