D DevBrainBox

HTML5 Canvas

HTML

What is HTML5 <canvas>?

The <canvas> element in HTML5 is used to draw graphics on the fly via JavaScript.

It’s like a blank area on your page where you can draw lines, shapes, images, charts, animations, and more.

<canvas id="myCanvas" width="400" height="200"></canvas>
  • It only defines a drawing area. It does not draw anything by itself.
  • To draw on it, you use JavaScript.

Example: Drawing a Rectangle

<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;">
    Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
    // Get the canvas element by ID
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d"); // Get the 2D drawing context

    // Draw a filled rectangle
    ctx.fillStyle = "#FF0000"; // Fill color
    ctx.fillRect(50, 50, 150, 100); // x, y, width, height
</script>
  • getContext("2d"): gets a 2D rendering context to draw shapes, lines, images etc.
  • fillStyle: sets the color to fill.
  • fillRect(x, y, width, height): draws a filled rectangle.

On this page