Canvas in HTML

  • Last updated Apr 25, 2024

The canvas element is a rectangular area on an HTML page where you can draw graphics, charts, animations, and more. It acts as a container for graphics and can be easily manipulated using JavaScript. To incorporate a canvas into your HTML document, you simply need to add the following code snippet:

<canvas id="myCanvas" width="500" height="300"></canvas>

Here, "myCanvas" is the identifier name for the canvas.  The width and height attributes can be used to set the dimensions of your canvas.

Drawing on the Canvas

After you've added a canvas to your HTML document, the next thing to do is use JavaScript to draw on it. The canvas API provides a bunch of methods that let you create shapes, text, and images. Here's a basic example of drawing a simple rectangle on the canvas:

<script>
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "green";
    ctx.fillRect(50, 50, 100, 75);
</script>

Here's the complete example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
    <title>HTML Canvas Example</title>
</head>
<body>
    <canvas id="myCanvas" width="500" height="300"></canvas>

    <script>
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "green";
        ctx.fillRect(50, 50, 100, 75);
    </script>

</body>
</html>

In this example, we retrieve the canvas element using its ID, get the 2D rendering context, set the fill color to blue, and then draw a filled rectangle with the specified dimensions.