Introduction to Canvas
Learn how to set up an HTML canvas, use its 2D context to draw and style shapes, apply transformations, and create animations.
Summary
Read Summary
Flashcards
Save Flashcards
Quiz
Take Quiz
Quick Practice
What is the primary purpose of the HTML canvas element?
1 of 19
Summary
Introduction to the Canvas Element
What is Canvas?
The canvas element is an HTML tag that creates a blank rectangular drawing surface where you can programmatically draw graphics using JavaScript. Think of it as a digital sketchpad—you provide the JavaScript code, and the canvas renders shapes, lines, images, and text based on your instructions.
Canvas is fundamentally different from other HTML elements. Rather than creating separate DOM elements (like you would with <div> or <span> tags), canvas draws directly onto a bitmap pixel buffer. This makes it efficient for graphics-heavy applications like games, data visualizations, and animations.
Setting the Size of Canvas
The canvas element has two essential attributes: width and height. These define the pixel dimensions of your drawing surface.
html
<canvas id="myCanvas" width="800" height="600"></canvas>
In this example, the canvas creates an 800-by-600 pixel drawing area. It's important to set these attributes directly on the canvas tag itself, rather than using CSS styling, because they define the actual resolution of the drawing surface.
Understanding the Bitmap Nature of Canvas
Canvas stores its content as a grid of pixels (a bitmap) rather than as individual, selectable objects. This has important implications: once you draw a shape on canvas, it becomes part of the pixel data. You cannot click on it, select it, or modify it individually—you can only redraw the entire canvas with new content. This is very different from SVG graphics, which maintain shapes as separate DOM elements.
Obtaining the 2-D Drawing Context
Getting Started: Select and Setup
Before you can draw anything on canvas, you need to access it from JavaScript and request a drawing context. Here's the two-step process:
javascript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
The first line uses document.getElementById() to find the canvas element by its ID. The second line calls the getContext() method, passing in the string '2d' to request a 2D drawing context.
What is the Context Object?
The context object (typically stored in a variable named ctx) is your gateway to all canvas drawing capabilities. It's an object that provides methods and properties for drawing shapes, setting colors, transforming coordinates, and more. When you call methods like ctx.fillRect() or ctx.arc(), you're calling methods on this context object.
2D vs. 3D Contexts
The string '2d' specifically requests a two-dimensional drawing context, which is the standard for 2D graphics. If you wanted to draw 3D graphics, you would pass 'webgl' to getContext() instead, but that's a more advanced topic beyond our current scope.
Core Drawing Methods
Drawing Filled Rectangles
The simplest shape to draw is a rectangle. The fillRect() method draws a solid, filled rectangle:
javascript
ctx.fillRect(x, y, w, h);
Here, (x, y) is the top-left corner of the rectangle, w is the width, and h is the height, all measured in pixels. For example:
javascript
ctx.fillRect(50, 50, 200, 100);
This draws a filled rectangle with its top-left corner at coordinates (50, 50), with a width of 200 pixels and a height of 100 pixels.
Drawing Rectangle Outlines
If you want just the border of a rectangle instead of a filled shape, use strokeRect():
javascript
ctx.strokeRect(x, y, w, h);
This draws only the outline, leaving the interior transparent. The thickness of the outline is controlled by the lineWidth property (discussed in the styling section).
Drawing Circles and Arcs
For curves, canvas uses a path-based approach. The arc() method creates a circular or arc path:
javascript
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
Here, (x, y) is the center of the circle, radius is the radius in pixels, startAngle and endAngle are angles in radians (where 0 is to the right, and angles increase clockwise), and anticlockwise is a boolean (true to draw counterclockwise, false for clockwise).
For example, to draw a circle:
javascript
ctx.beginPath();
ctx.arc(150, 150, 50, 0, Math.PI 2);
ctx.fill();
Notice that arc() doesn't immediately draw—it creates a path. You must call ctx.fill() or ctx.stroke() to render it.
Drawing Images
You can also draw existing images onto the canvas:
javascript
ctx.drawImage(image, dx, dy);
The image parameter is an image object (often loaded from an tag), and (dx, dy) specifies where the top-left corner of the image should be placed on the canvas.
Creating and Rendering Paths
For more complex shapes, canvas uses a path-based drawing model:
ctx.beginPath() starts a new path
Various methods like ctx.arc(), ctx.lineTo(), and ctx.moveTo() define the path's shape
ctx.fill() fills the path with the current fill color
ctx.stroke() draws the path's outline with the current stroke color
This approach allows you to combine multiple lines, curves, and shapes into a single path before rendering.
Styling and Transformations
Setting Colors for Fills and Strokes
Colors control what your shapes look like. Set the fill color (the interior color) with:
javascript
ctx.fillStyle = 'color';
Set the stroke color (the outline color) with:
javascript
ctx.strokeStyle = 'color';
Colors can be specified as color names ('red', 'blue'), hex codes ('#FF0000'), or RGB values ('rgb(255, 0, 0)'). For example:
javascript
ctx.fillStyle = '#FF5733';
ctx.fillRect(10, 10, 100, 100);
Controlling Line Thickness
The thickness of stroked lines is set with:
javascript
ctx.lineWidth = value;
The value is measured in pixels. A larger value creates thicker lines.
Transforming the Coordinate System
Canvas allows you to transform the entire coordinate system, which affects all subsequent drawing operations. This is powerful for creating complex animations and graphics.
Rotation: Rotate the coordinate system by an angle (in radians):
javascript
ctx.rotate(angle);
Scaling: Stretch or shrink the coordinate system:
javascript
ctx.scale(scaleX, scaleY);
Translation: Move the origin of the coordinate system:
javascript
ctx.translate(dx, dy);
For example, if you translate by (100, 50) and then draw a rectangle at (0, 0), the rectangle will actually appear at (100, 50) on the screen. These transformations are cumulative and affect all subsequent drawing.
Animation and Frame Redrawing
The Animation Loop Concept
To create animation on canvas, you don't move individual shapes—instead, you redraw the entire canvas for each frame. Here's the basic concept:
Clear the canvas
Update the position or properties of your objects
Redraw all objects at their new positions
Repeat 60 times per second (or whatever frame rate you target)
For example, to animate a moving rectangle:
javascript
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
x += 2;
ctx.fillRect(x, 50, 100, 100);
window.requestAnimationFrame(animate);
}
animate();
Using requestAnimationFrame
The window.requestAnimationFrame(callback) method schedules your callback function to run before the next screen refresh. This is the best way to create smooth animations because it synchronizes with the browser's refresh rate (typically 60 times per second).
javascript
window.requestAnimationFrame(callback);
Rather than using setTimeout() or setInterval(), always use requestAnimationFrame for animations. It's optimized for graphics, pauses when the tab is not visible, and provides better performance.
Important Limitation: Canvas and the DOM
Canvas Content is Not Part of the DOM Tree
A crucial distinction: shapes drawn on canvas are not DOM elements. They're pixels rendered on a bitmap. This means:
You cannot select or style individual shapes with CSS
You cannot access drawn shapes with document.getElementById() or similar DOM methods
You cannot add event listeners directly to a specific shape
If you need interactivity, you must manually check mouse coordinates and determine which shape (if any) was clicked
This is fundamentally different from creating <div> or <span> elements, which become part of the DOM tree. Canvas is a drawing surface, not a container for elements.
For interactive applications, you need to:
Track the state of your objects in JavaScript variables
Redraw the entire canvas each frame
Listen to mouse or touch events on the canvas element itself
Manually calculate which object (if any) is at the clicked coordinates
Flashcards
What is the primary purpose of the HTML canvas element?
To provide a blank rectangular drawing area for programmatic graphics.
Which attributes define the pixel dimensions of the drawing surface for a canvas tag?
The width and height attributes.
How is canvas content stored internally compared to standard HTML elements?
In a bitmap pixel buffer (rather than as separate HTML elements).
Which JavaScript method is used to obtain the drawing context object from a canvas element?
.getContext() (e.g., canvas.getContext('2d')).
What is the specific role of the context object (often named ctx) in canvas programming?
It provides the API and methods for drawing shapes, lines, images, and text.
What string argument must be passed to getContext to request a three-dimensional drawing context?
"webgl"
Why are shapes drawn on a canvas not directly accessible by standard DOM methods?
Because they do not become individual DOM elements.
Which method draws a solid, filled rectangle at coordinates $(x, y)$ with width $w$ and height $h$?
ctx.fillRect(x, y, w, h)
Which method is used to draw only the border (outline) of a rectangle?
ctx.strokeRect(x, y, w, h)
What are the parameters for the ctx.arc() method used to create circular paths?
$x, y, radius, startAngle, endAngle, anticlockwise$
Which method is used to copy an existing image onto the canvas at a specific position?
ctx.drawImage(image, dx, dy)
What are the basic steps required to create and render a custom path on a canvas?
1. ctx.beginPath() to start the path.
2. Define the path (e.g., with arcs or lines).
3. ctx.fill() or ctx.stroke() to render it.
Which property is used to set the color for subsequent fill operations?
ctx.fillStyle
Which property defines the thickness of lines drawn with stroke methods?
ctx.lineWidth
What unit of measurement is used for the angle in the ctx.rotate(angle) method?
Radians
Which transformation method moves the origin of the coordinate system?
ctx.translate(dx, dy)
Which method is used to stretch or shrink drawing operations horizontally and vertically?
ctx.scale(scaleX, scaleY)
What is the general workflow for creating an animation frame on a canvas?
The entire canvas is cleared and then completely redrawn.
Which browser method provides a high-performance loop for scheduling the next animation frame?
window.requestAnimationFrame(callback)
Quiz
Introduction to Canvas Quiz Question 1: Which method is used to obtain the 2‑D drawing context from a canvas element?
- canvas.getContext('2d') (correct)
- canvas.getContext('webgl')
- document.getElementById('myCanvas')
- ctx.beginPath()
Introduction to Canvas Quiz Question 2: Which canvas method draws a solid rectangle at a given position and size?
- ctx.fillRect(x, y, w, h) (correct)
- ctx.strokeRect(x, y, w, h)
- ctx.arc(x, y, radius, startAngle, endAngle)
- ctx.drawImage(image, dx, dy)
Introduction to Canvas Quiz Question 3: How do you set the fill color for subsequent canvas drawing operations?
- Assign a color to ctx.fillStyle (correct)
- Assign a color to ctx.strokeStyle
- Set ctx.lineWidth to a numeric value
- Call ctx.beginPath()
Introduction to Canvas Quiz Question 4: Which canvas method draws only the border of a rectangle at a given position and size?
- ctx.strokeRect(x, y, w, h) (correct)
- ctx.fillRect(x, y, w, h)
- ctx.rect(x, y, w, h)
- ctx.clearRect(x, y, w, h)
Introduction to Canvas Quiz Question 5: Which property sets the thickness of lines drawn with stroke methods?
- ctx.lineWidth = value (correct)
- ctx.strokeStyle = 'color'
- ctx.rotate(angle)
- ctx.translate(dx, dy)
Introduction to Canvas Quiz Question 6: Which of the following best describes the type of content that can be drawn on an HTML <canvas> element?
- Programmatically generated graphics using JavaScript (correct)
- Static SVG markup embedded in the HTML
- Plain text defined between the canvas tags
- Pre‑loaded image files displayed without scripting
Introduction to Canvas Quiz Question 7: What do the width and height attributes of the <canvas> tag specify?
- The pixel dimensions of the drawing surface (correct)
- The size of the canvas element in CSS percentages
- The default font size for text drawn on the canvas
- The thickness of the canvas border
Introduction to Canvas Quiz Question 8: In which form is canvas content stored internally?
- In a bitmap pixel buffer (correct)
- As a hierarchy of DOM elements
- In SVG path definitions
- As a collection of CSS style objects
Introduction to Canvas Quiz Question 9: What does the canvas 2‑D context object (commonly stored in a variable named <code>ctx</code>) provide?
- Methods for drawing shapes, lines, images, and text (correct)
- Direct access to the browser’s rendering engine source code
- An automatic conversion of canvas drawings to SVG
- A CSS stylesheet that styles the canvas element
Introduction to Canvas Quiz Question 10: Which string value requests a two‑dimensional drawing context from a canvas?
- "2d" (correct)
- "2D"
- "webgl"
- "canvas2d"
Introduction to Canvas Quiz Question 11: What does the method <code>ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)</code> create?
- A circular or arc path centered at (x, y) (correct)
- A rectangle at (x, y) with given width and height
- An image placed at (x, y)
- A text string drawn at (x, y)
Introduction to Canvas Quiz Question 12: Which method starts a new drawing path on the canvas?
- ctx.beginPath() (correct)
- ctx.closePath()
- ctx.moveTo()
- ctx.lineTo()
Introduction to Canvas Quiz Question 13: Which function provides a high‑performance way to schedule the next frame in a canvas animation loop?
- window.requestAnimationFrame(callback) (correct)
- setTimeout(callback, 16)
- setInterval(callback, 16)
- window.requestIdleCallback(callback)
Introduction to Canvas Quiz Question 14: In a typical canvas animation loop, what is usually done at the beginning of each new frame?
- The entire canvas is cleared and then all objects are redrawn (correct)
- Only the objects that moved are drawn
- CSS transitions are applied to the canvas element
- New drawing commands are appended without clearing previous content
Introduction to Canvas Quiz Question 15: Which of the following statements correctly sets the stroke color to a semi‑transparent red?
- ctx.strokeStyle = 'rgba(255,0,0,0.5)'; (correct)
- ctx.strokeStyle = '#FF0000FF';
- ctx.strokeColor = 'red';
- ctx.stroke = 'rgba(255,0,0,0.5)';
Introduction to Canvas Quiz Question 16: Which canvas context function should be called to rotate the drawing coordinate system by a given angle in radians?
- ctx.rotate(angle) (correct)
- ctx.scale(sx, sy)
- ctx.translate(dx, dy)
- ctx.save()
Which method is used to obtain the 2‑D drawing context from a canvas element?
1 of 16
Key Concepts
Canvas Basics
HTML canvas element
Canvas 2D rendering context
Canvas drawing methods
Canvas transformations
Bitmap graphics
Animation and Graphics
requestAnimationFrame
WebGL
Web Technologies
Document Object Model (DOM)
Cascading Style Sheets (CSS)
Definitions
HTML canvas element
An HTML <canvas> tag that provides a blank bitmap area for script‑driven rendering of graphics.
Canvas 2D rendering context
The object returned by canvas.getContext('2d') that supplies the standard 2‑D drawing API.
Canvas drawing methods
Functions such as fillRect, strokeRect, arc, drawImage, fill, and stroke used to render shapes and images on a canvas.
Canvas transformations
Operations like rotate, scale, and translate that modify the canvas coordinate system for drawing.
requestAnimationFrame
A browser API that schedules a callback before the next repaint, enabling smooth animation loops.
WebGL
A JavaScript API for rendering interactive 3‑D graphics within an HTML <canvas> element using OpenGL ES.
Bitmap graphics
Pixel‑based images stored as a grid of color values, which is how canvas content is internally represented.
Document Object Model (DOM)
A programming interface for HTML and XML documents that represents page structure as a tree of nodes.
Cascading Style Sheets (CSS)
A stylesheet language used to describe the presentation and layout of HTML elements, though canvas drawings themselves are not part of the DOM.