RemNote Community
Community

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

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)