Home ยป HTML Canvas Drawing Rectangles Tutorial

HTML Canvas Drawing Rectangles Tutorial

by shedders

The HTML5 <canvas> element provides an API for drawing rectangles. Rectangles are the simplest and most commonly used shapes in canvas drawings.

You can draw filled rectangles, outlined rectangles, and even clear parts of the canvas using rectangle-related methods.

1. Rectangles in Canvas

The Canvas API provides three primary methods for working with rectangles:

  1. fillRect(x, y, width, height): Draws a filled rectangle.
  2. strokeRect(x, y, width, height): Draws an outlined rectangle.
  3. clearRect(x, y, width, height): Clears a rectangular area on the canvas.

Example 1: Basic Rectangle Methods

<canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas>
<script>
    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");

    // Filled rectangle
    ctx.fillStyle = "blue";
    ctx.fillRect(50, 50, 150, 100);

    // Outlined rectangle
    ctx.strokeStyle = "red";
    ctx.lineWidth = 4;
    ctx.strokeRect(250, 50, 150, 100);

    // Clear a part of the canvas
    ctx.clearRect(100, 75, 50, 50);
</script>

Explanation:

  • fillRect(x, y, width, height): Draws a solid rectangle.
  • strokeRect(x, y, width, height): Draws only the border of the rectangle.
  • clearRect(x, y, width, height): Erases the specified rectangular area.

2. Drawing Multiple Rectangles

You can create grids or complex patterns by combining rectangle methods.

Example 2: Drawing a Grid of Rectangles

for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; j++) {
        ctx.fillStyle = `rgb(${i * 50}, ${j * 50}, 150)`;
        ctx.fillRect(50 + i * 50, 50 + j * 50, 40, 40);
    }
}

3. Adding Transparency with RGBA

Rectangles can be drawn with transparency using RGBA colors.

Example 3: Transparent Rectangles

ctx.fillStyle = "rgba(255, 0, 0, 0.5)"; // Red with 50% opacity
ctx.fillRect(50, 50, 100, 100);

ctx.fillStyle = "rgba(0, 0, 255, 0.5)"; // Blue with 50% opacity
ctx.fillRect(100, 100, 100, 100);

Explanation:

  • The a (alpha) in RGBA controls the transparency. 0 is fully transparent, and 1 is fully opaque.

4. Combining Fill and Stroke

You can use both fillRect and strokeRect to create filled rectangles with outlines.

Example 4: Combining Fill and Stroke

ctx.fillStyle = "yellow";
ctx.fillRect(150, 150, 100, 60);

ctx.strokeStyle = "black";
ctx.lineWidth = 3;
ctx.strokeRect(150, 150, 100, 60);

5. Rounded Rectangles

Canvas does not provide a built-in method for rounded rectangles, but you can create them using paths.

Example 5: Drawing Rounded Rectangles

function drawRoundedRect(ctx, x, y, width, height, radius) {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + width - radius, y);
    ctx.arcTo(x + width, y, x + width, y + radius, radius);
    ctx.lineTo(x + width, y + height - radius);
    ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
    ctx.lineTo(x + radius, y + height);
    ctx.arcTo(x, y + height, x, y + height - radius, radius);
    ctx.lineTo(x, y + radius);
    ctx.arcTo(x, y, x + radius, y, radius);
    ctx.closePath();
}

ctx.fillStyle = "lightgreen";
drawRoundedRect(ctx, 50, 50, 150, 100, 20);
ctx.fill();

ctx.strokeStyle = "darkgreen";
ctx.lineWidth = 3;
drawRoundedRect(ctx, 250, 50, 150, 100, 30);
ctx.stroke();

Explanation:

  • arcTo(x1, y1, x2, y2, radius) creates the rounded corners.

6. Animating Rectangles

You can animate rectangles by repeatedly redrawing them in different positions.

Example 6: Moving Rectangle Animation

let x = 0;
let speed = 2;

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = "purple";
    ctx.fillRect(x, 100, 100, 50);

    x += speed;
    if (x + 100 > canvas.width || x < 0) {
        speed = -speed; // Reverse direction
    }

    requestAnimationFrame(animate);
}

animate();

Explanation:

  • requestAnimationFrame provides smooth animations by redrawing at the appropriate frame rate.
  • clearRect prevents trails by erasing the previous frame.

7. Practical Example: Bar Chart

Example 7: Drawing a Bar Chart

const data = [50, 120, 90, 180, 140];
const colors = ["red", "blue", "green", "orange", "purple"];

data.forEach((value, index) => {
    ctx.fillStyle = colors[index];
    ctx.fillRect(50 + index * 60, 300 - value, 40, value);

    // Add labels
    ctx.fillStyle = "black";
    ctx.fillText(value, 50 + index * 60 + 10, 300 - value - 10);
});

Explanation:

  • Each bar represents a data value, drawn at a calculated height.
  • The fillText method is used to add labels to the bars.

8. Best Practices for Drawing Rectangles

  1. Clear Before Redrawing:
    • Always clear the canvas (clearRect) before redrawing, especially for animations.
  2. Use save and restore:
    • Wrap complex transformations (e.g., rotations or translations) with save() and restore() to avoid affecting unrelated drawings.
  3. Reuse Functions:
    • Use reusable functions for patterns like grids, rounded rectangles, or bar charts.

9. Browser Support

All modern browsers support rectangle methods in the Canvas API:

Feature Supported?
fillRect Yes
strokeRect Yes
clearRect Yes

10. Conclusion

In this tutorial, you learned:

  1. How to draw and style rectangles using fillRect, strokeRect, and clearRect.
  2. How to create rounded rectangles.
  3. How to animate rectangles and use them in practical applications like bar charts.

 

You may also like