Understanding the HTML Canvas Element
The HTML <canvas> element creates a drawing surface that JavaScript can use to generate graphics dynamically.
Canvas can be used for shapes, charts, animations, games, image manipulation, and other graphics that need to be created or changed while a webpage is running.
The <canvas> Element
The <canvas> element defines a rectangular area where graphics can be drawn with JavaScript. By itself, the element creates the drawing surface but does not draw anything.
<canvas id="exampleCanvas" width="600" height="300"></canvas>
The id gives JavaScript a convenient way to locate the canvas so that a drawing context can be created and graphics can be added.
Canvas Width and Height
The width and height attributes set the dimensions of the canvas drawing surface.
<canvas width="600" height="300"></canvas>
The default canvas size is 300 pixels wide by 150 pixels high when these attributes are omitted.
Setting the drawing dimensions with the HTML attributes is important. Changing only the CSS width or height scales the existing drawing surface and can distort the graphics.
The Drawing Context
JavaScript first obtains a reference to the canvas and then requests a drawing context. For ordinary two-dimensional graphics, use the 2d context.
const canvas = document.getElementById("exampleCanvas");
const ctx = canvas.getContext("2d");
The context provides the methods and properties used to draw shapes, lines, text, images, and other graphics on the canvas.
Canvas Coordinates
Canvas uses an x and y coordinate system. The point 0, 0 is located at the upper-left corner of the drawing surface.
The x-coordinate increases as you move to the right, while the y-coordinate increases as you move downward.
ctx.fillRect(50, 40, 200, 100);
In this example, the rectangle begins 50 pixels from the left and 40 pixels from the top of the canvas.
Drawing Rectangles
The canvas 2D context includes methods for drawing filled and outlined rectangles.
ctx.fillRect(50, 40, 200, 100);
ctx.strokeRect(300, 40, 200, 100);
The four values represent the x-coordinate, y-coordinate, width, and height of the rectangle.
The clearRect() method can also clear a rectangular portion of the canvas.
ctx.clearRect(75, 65, 50, 50);
Drawing Lines
Lines and more complex shapes are created with paths. A path is started with beginPath(), followed by commands that define where the path should move and draw.
ctx.beginPath();
ctx.moveTo(50, 200);
ctx.lineTo(550, 200);
ctx.stroke();
The moveTo() method positions the starting point without drawing, lineTo() adds a line to another point, and stroke() makes the path visible.
Canvas Colors
The fillStyle property controls the color used to fill shapes, while strokeStyle controls the color used for outlines and lines.
ctx.fillStyle = "#0088cc";
ctx.fillRect(50, 40, 200, 100);
ctx.strokeStyle = "#02bf57";
ctx.strokeRect(300, 40, 200, 100);
Canvas accepts familiar CSS color values, including hexadecimal, RGB, HSL, and named colors.
Drawing Text
Text can be drawn directly onto the canvas with methods such as fillText() and strokeText().
ctx.font = "24px Arial";
ctx.fillStyle = "#000000";
ctx.fillText("Hello, Canvas!", 50, 250);
The font property uses CSS-style font values, while the coordinates determine where the text is drawn.
Fallback Content
The <canvas> element can contain fallback content between its opening and closing tags.
<canvas id="exampleCanvas" width="600" height="300">
Your browser does not support the HTML canvas element.
</canvas>
Fallback content is shown when canvas is not supported. It can also provide an alternative representation when important information would otherwise exist only as pixels drawn on the canvas.
Canvas Accessibility
Graphics drawn on a canvas are pixels rather than ordinary HTML elements, so their meaning is not automatically available to assistive technology. Important information should not be communicated only through canvas graphics.
When a canvas contains meaningful information, provide an accessible alternative using appropriate HTML, text, controls, or other content that communicates the same information.
For example, a chart drawn on a canvas may also need a data table or text summary that presents the same information in an accessible form.
HTML Canvas Example
The following example creates a canvas and uses JavaScript to draw two rectangles, a line, and text. Change the coordinates, dimensions, and colors in the editor to see how the drawing changes.
HTML Canvas Best Practices
- Set the canvas drawing dimensions with the
widthandheightattributes. - Use CSS for layout and responsive presentation without unintentionally distorting the drawing surface.
- Use meaningful variable names when working with the canvas and its drawing context.
- Remember that canvas coordinates begin at the upper-left corner.
- Provide accessible alternatives when the canvas communicates meaningful information.
- Use ordinary HTML and CSS instead of canvas when standard elements can represent the content appropriately.
- Keep complex drawing and animation code organized in separate JavaScript files when appropriate.
Summary
The HTML <canvas> element provides a drawing surface for graphics generated with JavaScript. A 2D drawing context can create rectangles, lines, paths, text, images, animations, and many other types of dynamic graphics.
Canvas is useful when graphics need to be generated or manipulated programmatically, but meaningful information displayed on a canvas should also have an accessible alternative.
