Home ยป HTML Canvas – The Canvas Element Tutorial

HTML Canvas – The Canvas Element Tutorial

by shedders

The HTML5 <canvas> element is a powerful feature that allows you to create and manipulate 2D or 3D graphics using JavaScript.

It can be used for drawing shapes, images, text, animations, and even interactive graphics like games.

In this tutorial, you’ll learn:

  1. What is the <canvas> element?
  2. How to set up a canvas in HTML.
  3. Drawing basic shapes.
  4. Adding styles to the canvas.
  5. Handling canvas resizing.
  6. Practical examples of canvas usage.

1. What is the <canvas> Element?

The <canvas> element is an HTML tag that defines a rectangular area where graphics can be drawn using JavaScript.

  • It requires a width and height attribute to define the size.
  • All drawings on the canvas are performed using the CanvasRenderingContext2D API.

2. Setting Up a Canvas

You must define a canvas in your HTML and get its context using JavaScript.

Example 1: Basic Canvas Setup

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

Explanation:

  • <canvas>: The HTML tag for the canvas.
  • getContext(“2d”): Returns a rendering context to draw 2D graphics.

3. Drawing Basic Shapes

The canvas API provides methods to draw rectangles, lines, circles, and more.

Example 2: Drawing a Rectangle

ctx.fillStyle = "blue"; // Set the fill color
ctx.fillRect(50, 50, 150, 100); // Draw a filled rectangle

Example 3: Drawing a Line

ctx.beginPath();
ctx.moveTo(50, 200); // Start point
ctx.lineTo(200, 200); // End point
ctx.strokeStyle = "red"; // Line color
ctx.lineWidth = 3; // Line thickness
ctx.stroke();

Example 4: Drawing a Circle

ctx.beginPath();
ctx.arc(300, 150, 50, 0, Math.PI * 2); // Circle: (x, y, radius, startAngle, endAngle)
ctx.fillStyle = "green";
ctx.fill(); // Fill the circle

4. Adding Styles to the Canvas

The canvas API allows you to customize fills, strokes, and line styles.

Example 5: Adding Gradients

const gradient = ctx.createLinearGradient(0, 0, 500, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "yellow");

ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 500, 300);

Explanation:

  • createLinearGradient(x0, y0, x1, y1): Creates a gradient between two points.
  • addColorStop(position, color): Adds colors at specific points in the gradient.

Example 6: Adding Shadows

ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;

ctx.fillStyle = "blue";
ctx.fillRect(100, 100, 200, 100);

5. Resizing the Canvas

When resizing the canvas, you need to redraw everything because resizing clears the canvas.

Example 7: Dynamic Canvas Resizing

function resizeCanvas() {
    canvas.width = window.innerWidth; // Set canvas width to window width
    canvas.height = window.innerHeight; // Set canvas height to window height

    // Redraw content
    ctx.fillStyle = "lightgray";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "blue";
    ctx.fillRect(100, 100, 200, 100);
}

window.addEventListener("resize", resizeCanvas);
resizeCanvas();

6. Interactivity with Canvas

Canvas can respond to mouse and keyboard events.

Example 8: Drawing on Canvas with Mouse

let isDrawing = false;

canvas.addEventListener("mousedown", () => (isDrawing = true));
canvas.addEventListener("mouseup", () => (isDrawing = false));
canvas.addEventListener("mousemove", (event) => {
    if (isDrawing) {
        ctx.fillStyle = "black";
        ctx.beginPath();
        ctx.arc(event.offsetX, event.offsetY, 5, 0, Math.PI * 2);
        ctx.fill();
    }
});

7. Practical Examples

Example 9: A Simple 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 * 70, 300 - value, 50, value);

    ctx.fillStyle = "black";
    ctx.fillText(value, 50 + index * 70 + 15, 300 - value - 10);
});

Example 10: Bouncing Ball Animation

let x = 50;
let y = 50;
let dx = 2; // Horizontal velocity
let dy = 2; // Vertical velocity
const radius = 20;

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

    // Draw the ball
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    ctx.fillStyle = "blue";
    ctx.fill();

    // Update position
    x += dx;
    y += dy;

    // Bounce off edges
    if (x + radius > canvas.width || x - radius < 0) dx = -dx;
    if (y + radius > canvas.height || y - radius < 0) dy = -dy;

    requestAnimationFrame(animate);
}

animate();

8. Best Practices for Using Canvas

  1. Optimize Performance:
    • Minimize the area cleared or redrawn in animations.
    • Use off-screen canvas for complex drawings.
  2. Maintain Resolution:
    • Use CSS to scale the canvas, but match the width and height attributes to the drawing resolution.
  3. Separate Logic:
    • Keep drawing logic separate from event handling or data processing.

9. Browser Support

The <canvas> element and its API are widely supported in all modern browsers:

Feature Supported?
<canvas> Element Yes
getContext(“2d”) Yes
Animations & Interactivity Yes

10. Conclusion

In this tutorial, you learned:

  1. How to set up the <canvas> element.
  2. How to draw basic shapes, add styles, and resize dynamically.
  3. How to make canvas interactive and use it for practical applications like charts and animations.

 

You may also like