HTML Mastery — Chapter 12: HTML Canvas 2D Graphics
Section 4 · Chapter 12
HTML Canvas 2D Graphics
The HTML <canvas> element provides an immediate-mode bitmap surface for drawing real-time 2D graphics, vector shapes, charts, image filters, and game animations using JavaScript's CanvasRenderingContext2D API.
Live Code Example
Click Try it Yourself » to execute JavaScript canvas drawing commands live in the interactive playground environment.
Example: Drawing Shapes, Gradients & Text on Canvas
12.1 The <canvas> Element & 2D Context (getContext('2d'))
The <canvas> element is a container for graphics. You must use JavaScript to draw on the bitmap buffer surface. The JavaScript method canvas.getContext('2d') obtains the built-in 2D rendering context object containing all drawing properties and algorithms.
Canvas Attributes vs CSS Sizing: Canvas internal resolution is defined strictly using HTML attributes (e.g., width="400" height="200"). Setting canvas width/height solely in CSS will stretch the pixel buffer and blur the graphic output.
Canvas 2D Coordinate Grid System & Raster Pixel Buffer
The 2D context provides three helper methods to draw rectangles directly, as well as low-level path commands (beginPath(), moveTo(), lineTo(), closePath()) to create sub-paths and vector polygons.
Method
Description
Example
fillRect(x, y, w, h)
Draws a filled rectangle using current fillStyle.
ctx.fillRect(20, 20, 100, 50);
strokeRect(x, y, w, h)
Draws an outlined rectangle using strokeStyle & lineWidth.
ctx.strokeRect(140, 20, 100, 50);
clearRect(x, y, w, h)
Clears pixels in specified rectangle, setting them to transparent black.
ctx.clearRect(40, 30, 40, 30);
beginPath() / stroke()
Resets current sub-path list and draws path stroke line.
Circles and circular arcs are created using the arc(x, y, radius, startAngle, endAngle, counterclockwise) method. Angles in Canvas 2D are measured in radians (radians = (degrees * Math.PI) / 180).
Immediate Mode Bitmap: The <canvas> element draws pixels directly into a 32-bit raster buffer. It does not create individual DOM elements for shapes.
Coordinate Origin: The (0,0) origin is located at the top-left corner of the canvas viewport.
2D Context API: Obtain the drawing context using canvas.getContext('2d') to access methods like fillRect(), strokeRect(), arc(), createLinearGradient(), and fillText().
Path Lifecycle: Path drawing must start with beginPath() and finalize with stroke() or fill().
Done with this
chapter?
Mark it complete to track your progress and unlock
your certificate.
🧠
Test
Your Knowledge
Next Up
—
Learner Reviews
—
No reviews yet. Be the first to review this course!