HTML Canvas

The <canvas> element allows you to draw graphics and animations using JavaScript. It provides a rectangular area where you can dynamically render shapes, text, images, and more, making it ideal for interactive charts, games, and visualizations.

Key Topics

Basic Usage

Example: A simple canvas element with width and height attributes.

<canvas id="myCanvas" width="400" height="200"></canvas>

Canvas Drawing API

Use JavaScript to access the canvas context and call drawing methods like fillRect(), strokeText(), and moveTo(), lineTo() to render shapes and text.

Canvas Example

This example draws a simple rectangle and text on the canvas. A full code sample is provided below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Canvas Example</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
        var c = document.getElementById('myCanvas');
        var ctx = c.getContext('2d');
        ctx.fillStyle = '#00f';
        ctx.fillRect(50, 50, 100, 50);
        ctx.fillStyle = '#000';
        ctx.font = '20px Arial';
        ctx.fillText('Hello Canvas!', 50, 140);
    </script>
</body>
</html>

Explanation: The JavaScript code gets the 2D context of the canvas and draws a blue rectangle and text, showcasing basic drawing capabilities.

Key Takeaways

  • The <canvas> provides a drawable surface for dynamic graphics.
  • Use JavaScript and the 2D context API to draw shapes, text, and images.
  • Canvas is pixel-based, offering low-level control over rendering.
  • Ideal for animations, games, data visualizations, and custom graphics.
  • Requires scripting; no built-in shapes without JavaScript.