HTML for Web Development

0% completed

Previous
Next
HTML - Canvas Element

In this lesson, you'll learn about the <canvas> element, which enables you to draw graphics on the fly using scripting (typically JavaScript). While a basic understanding of JavaScript can help you fully grasp how to control the canvas, we'll provide a simple example suitable for beginners.

What Is the <canvas> Element?

The <canvas> element is a container for graphics. You can draw shapes, text, images, and animations within this element using JavaScript. The canvas itself is simply a drawing surface; it does not provide drawing capabilities on its own.

Basic Syntax:

<canvas id="myCanvas" width="300" height="150"> Your browser does not support the HTML5 canvas tag. </canvas>
  • id Attribute: Used to reference the canvas in JavaScript.
  • width and height Attributes: Define the dimensions of the canvas.

A Simple Example With JavaScript

Below is a simple example that draws a rectangle on the canvas.

  • Note: This example uses a small bit of JavaScript to interact with the canvas. If you have some knowledge of JavaScript, you'll see that the code is straightforward and helps you control what appears on the canvas.
HTML

. . . .

Explanation:

  • Canvas Element:
    The <canvas> element with id="myCanvas" creates a 300x150 pixel drawing area.

  • JavaScript Section:

    • document.getElementById("myCanvas"): Retrieves the canvas element.
    • canvas.getContext("2d"): Gets the 2D drawing context, which is used to draw shapes.
    • ctx.fillStyle and ctx.fillRect(...): Set the fill color and draw a filled rectangle.
    • ctx.strokeStyle, ctx.lineWidth, and ctx.strokeRect(...): Set the border color and width, then draw a border around the rectangle.

The <canvas> element is a powerful feature of HTML5, opening up many possibilities for dynamic graphics and animations. As you advance, you can explore more complex drawings and interactive animations using JavaScript with the canvas.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next