HTML Canvas
Learn how to use the HTML Canvas element to draw dynamic graphics, shapes, text, images, games, and animations using JavaScript.
Introduction
In the previous lesson, you learned about SVG and how vector graphics can be created using shapes, coordinates, and markup.
SVG is excellent for logos, icons, diagrams, charts, and graphics that must remain sharp at different sizes.
However, some applications need to redraw large amounts of visual content continuously.
Browser games, particle effects, drawing applications, real-time visualizations, image editors, and complex animations often require graphics to change many times every second.
For these situations, HTML provides the <canvas> element.
Canvas creates a blank pixel-based drawing surface. JavaScript then controls what is drawn, where it appears, how it looks, and when it changes.
SVG
- Graphics are represented by individual elements.
- Vector-based rendering.
- Excellent for logos and diagrams.
- Individual shapes remain accessible in the DOM.
Canvas
- Graphics are drawn onto one surface.
- Pixel-based rendering.
- Excellent for games and dynamic scenes.
- JavaScript controls the drawing process.
The <canvas> element only creates the drawing surface. JavaScript performs the actual drawing.
What is Canvas?
HTML Canvas is a rectangular drawing area created using the <canvas> element.
It provides a pixel-based surface where JavaScript can draw graphics dynamically.
Canvas can be used to draw rectangles, lines, circles, paths, text, images, charts, animations, game scenes, and many other visual elements.
Unlike normal HTML elements, the objects drawn on a canvas do not automatically become separate DOM elements.
<canvas
id="myCanvas"
width="400"
height="300"
>
</canvas>const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 150, 100);Drawing Surface
Canvas provides an area where graphics can be painted.
JavaScript Controlled
Drawing commands are normally executed through JavaScript.
Pixel-Based
The rendered result behaves like a bitmap of pixels.
Dynamic
The canvas can be cleared and redrawn repeatedly.
Interactive
User input can control what appears on the canvas.
Image Capable
Images can be drawn, transformed, cropped, and manipulated.
Canvas is a blank HTML drawing surface that JavaScript can use to create and update pixel-based graphics.
Why Do We Need Canvas?
Modern web applications often need graphics that change continuously in response to time, data, physics, animation, or user interaction.
Creating thousands of separate HTML or SVG elements can become inefficient for certain highly dynamic scenes.
Canvas provides a drawing surface that can be updated directly through JavaScript.
Without Canvas
- Complex browser games become harder to render efficiently.
- Particle effects may require many separate elements.
- Pixel-level image manipulation becomes difficult.
- Dynamic drawing tools require more complicated approaches.
- Frequently changing scenes can create heavy DOM structures.
With Canvas
- Create dynamic 2D game scenes.
- Render large numbers of changing objects.
- Build drawing and painting applications.
- Manipulate image pixels.
- Create real-time charts and animations.
Games
Render characters, backgrounds, effects, and game worlds.
Animations
Redraw scenes repeatedly to create motion.
Particle Effects
Display large numbers of moving visual objects.
Drawing Apps
Create sketch boards, signature pads, and paint tools.
Image Processing
Read and manipulate image pixel data.
Live Visualizations
Render graphics that update continuously with data.
Real-World Analogy
Imagine a physical painting canvas.
The canvas begins as an empty surface. A painter uses brushes, colors, and drawing techniques to create the final artwork.
HTML Canvas works in a similar way.
The <canvas> element provides the blank surface, the drawing context provides the tools, and JavaScript acts like the artist controlling those tools.
| Physical Drawing | HTML Canvas |
|---|---|
| Blank Canvas | <canvas> element |
| Painter | JavaScript |
| Brushes and Tools | Drawing context methods |
| Paint Colors | Style properties |
| Brush Movement | Coordinates |
| Artwork | Rendered pixels |
Physical Canvas HTML Canvas
─────────────── ───────────
Blank Board <canvas> Element
Artist JavaScript
Paintbrush Drawing Context
Brush Position X-Y Coordinates
Paint Colors & Styles
Artwork Rendered GraphicsAfter a shape is painted, Canvas mainly contains the resulting pixels. It does not automatically maintain each painted shape as a separate HTML element.
HTML Canvas Element
The <canvas> element creates the drawing surface.
By itself, the element does not draw anything.
<canvas
id="myCanvas"
width="400"
height="300"
>
Your browser does not support the canvas element.
</canvas>| Part | Purpose |
|---|---|
| <canvas> | Creates the drawing surface |
| id | Allows JavaScript to select the canvas |
| width | Defines the internal drawing width |
| height | Defines the internal drawing height |
| Fallback Content | Displayed if Canvas is unsupported |
The width and height attributes define the internal pixel dimensions of the drawing surface.
<canvas
id="myCanvas"
width="400"
height="300"
style="border: 1px solid black;"
>
</canvas>The width and height attributes control the internal drawing resolution. CSS width and height control only how large the canvas appears on the page.
Canvas Coordinate System
Canvas uses a two-dimensional X-Y coordinate system.
The coordinate origin begins at the top-left corner of the drawing surface.
The top-left corner is represented by the coordinate (0,0).
Positive X values move toward the right, while positive Y values move downward.
(0,0) ───────────────────────→ X
│
│
│ ● (100,100)
│
│
│
▼
Y| Direction | Coordinate Change |
|---|---|
| Move Right | X increases |
| Move Left | X decreases |
| Move Down | Y increases |
| Move Up | Y decreases |
ctx.fillRect(
50, // X position
40, // Y position
150, // Width
100 // Height
);Just like SVG, the default Canvas coordinate system increases Y values as you move downward.
Accessing the Canvas
JavaScript must access the canvas before drawing can begin.
The process normally requires two steps: selecting the <canvas> element and requesting a drawing context.
<canvas
id="myCanvas"
width="400"
height="300"
>
</canvas>const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");| Code | Purpose |
|---|---|
| document.getElementById("myCanvas") | Selects the canvas element |
| canvas.getContext("2d") | Requests the 2D drawing context |
| ctx | Stores the object used for drawing commands |
The 2D context provides methods and properties for drawing shapes, paths, text, and images.
Example 1: Drawing a Rectangle
The fillRect() method draws a filled rectangle.
ctx.fillStyle = "blue";
ctx.fillRect(
50,
40,
150,
100
);| Value | Meaning |
|---|---|
| 50 | X position |
| 40 | Y position |
| 150 | Rectangle width |
| 100 | Rectangle height |
// Filled rectangle
ctx.fillRect(x, y, width, height);
// Outlined rectangle
ctx.strokeRect(x, y, width, height);
// Clear rectangular area
ctx.clearRect(x, y, width, height);Set fillStyle before calling fillRect() to control the color of the rectangle.
Example 2: Drawing a Line
Lines are created using paths.
A path begins with beginPath(), moves to a starting coordinate, continues to another coordinate, and is finally rendered using stroke().
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(250, 150);
ctx.stroke();| Method | Purpose |
|---|---|
| beginPath() | Starts a new path |
| moveTo(x, y) | Moves to the starting position |
| lineTo(x, y) | Creates a line toward another point |
| stroke() | Draws the path outline |
Example 3: Drawing a Circle
Canvas does not provide a dedicated circle element.
Instead, circles and arcs are created using the arc() method.
ctx.beginPath();
ctx.arc(
120,
100,
50,
0,
2 * Math.PI
);
ctx.stroke();| Argument | Meaning |
|---|---|
| 120 | X coordinate of the center |
| 100 | Y coordinate of the center |
| 50 | Radius |
| 0 | Starting angle |
| 2 * Math.PI | Ending angle for a full circle |
Outline Circle
- Create the arc path.
- Call stroke().
- Uses the current stroke style.
Filled Circle
- Create the arc path.
- Set fillStyle.
- Call fill().
ctx.beginPath();
ctx.arc(
120,
100,
50,
0,
2 * Math.PI
);
ctx.fillStyle = "blue";
ctx.fill();Example 4: Drawing Text
Canvas can draw text using fillText() and strokeText().
ctx.font = "30px Arial";
ctx.fillText(
"Hello Canvas",
40,
70
);| Part | Purpose |
|---|---|
| ctx.font | Controls font size and family |
| fillText() | Draws filled text |
| "Hello Canvas" | Text content |
| 40 | X position |
| 70 | Y baseline position |
// Filled text
ctx.fillText("Hello Canvas", 40, 70);
// Outlined text
ctx.strokeText("Hello Canvas", 40, 70);Use ctx.font before calling fillText() or strokeText() to control the text appearance.
Example 5: Drawing an Image
Canvas can draw images using the drawImage() method.
The image must finish loading before it is drawn.
const img = new Image();
img.src = "logo.png";
img.onload = function () {
ctx.drawImage(
img,
20,
20
);
};ctx.drawImage(
img,
20,
20,
200,
100
);| Argument | Purpose |
|---|---|
| img | Image to draw |
| 20 | X position |
| 20 | Y position |
| 200 | Displayed width |
| 100 | Displayed height |
Calling drawImage() before the image has loaded can result in nothing being drawn.
Complete Canvas Example
The following example combines HTML and JavaScript to create a complete canvas drawing.
<canvas
id="myCanvas"
width="400"
height="250"
style="border: 1px solid black;"
>
</canvas>
<script>
const canvas =
document.getElementById("myCanvas");
const ctx =
canvas.getContext("2d");
// Draw rectangle
ctx.fillStyle = "green";
ctx.fillRect(
40,
40,
150,
100
);
// Draw text
ctx.font = "24px Arial";
ctx.fillStyle = "black";
ctx.fillText(
"Canvas Demo",
40,
180
);
</script>Canvas executes drawing instructions sequentially. Later commands can paint over pixels created by earlier commands.
Canvas Drawing Process
Most Canvas programs follow the same basic workflow.
// 1. Select canvas
const canvas =
document.getElementById("myCanvas");
// 2. Get context
const ctx =
canvas.getContext("2d");
// 3. Configure drawing style
ctx.fillStyle = "blue";
// 4. Draw
ctx.fillRect(
50,
50,
150,
100
);| Stage | Question |
|---|---|
| Create | Where will graphics be drawn? |
| Select | Which canvas should JavaScript control? |
| Context | Which drawing system will be used? |
| Style | How should the graphic look? |
| Draw | What should appear? |
| Render | Which pixels should the browser display? |
Canvas development is a sequence of commands that change the current drawing state and paint pixels onto the surface.
Canvas vs SVG
Canvas and SVG can both create graphics, but they use fundamentally different rendering models.
| Feature | Canvas | SVG |
|---|---|---|
| Rendering Model | Pixel-based drawing surface | Vector-based elements |
| Technology | Primarily JavaScript drawing commands | SVG markup and DOM elements |
| Object Model | Drawn objects are not automatically separate DOM nodes | Each shape can be a DOM element |
| Scaling | Can become blurry if scaled incorrectly | Remains sharp when scaled |
| Interaction | Usually handled manually with coordinates | Individual elements can receive events |
| Large Dynamic Scenes | Often well suited | Can become expensive with many DOM elements |
| Accessibility | Requires additional planning | Individual elements can provide more structure |
| Best For | Games, particles, image processing | Logos, icons, diagrams |
| Animation | Redraw frames using JavaScript | Animate individual vector elements |
| Pixel Manipulation | Supported | Not the primary model |
Choose Canvas For
- Browser games.
- Particle systems.
- Drawing applications.
- Image processing.
- Frequently changing scenes.
- Large numbers of visual objects.
Choose SVG For
- Logos.
- Icons.
- Diagrams.
- Interactive vector maps.
- Scalable illustrations.
- Graphics with individually interactive shapes.
Choose Canvas or SVG according to the rendering model, interaction requirements, accessibility needs, scalability, and performance characteristics of the application.
Browser Rendering Flow
When the browser processes a canvas application, the HTML element creates the surface and JavaScript provides the drawing instructions.
HTML Document
│
▼
Find <canvas>
│
▼
Create Blank Surface
│
▼
Run JavaScript
│
▼
Get 2D Context
│
▼
Execute Drawing Commands
│
▼
Update Pixels
│
▼
Display CanvasSVG Rendering
- Browser reads vector elements.
- Each shape can remain a DOM object.
- Geometry is recalculated during scaling.
Canvas Rendering
- JavaScript issues drawing commands.
- The result is painted onto one surface.
- Changing a scene usually requires redrawing.
JavaScript tells the canvas what to draw now. The application must manage object state separately if those objects need to move or change later.
Real-World Applications
Canvas is widely used for dynamic and interactive visual applications.
Browser Games
Characters, worlds, effects, projectiles, and game interfaces.
Drawing Applications
Paint tools, sketch boards, whiteboards, and signature pads.
Image Editing
Cropping, resizing, filtering, and pixel manipulation.
Real-Time Charts
Frequently updating graphs and visual dashboards.
Particle Systems
Smoke, sparks, snow, stars, and visual effects.
Data Visualizations
Large and continuously changing visual datasets.
Video Processing
Capture and process video frames.
Simulations
Physics, scientific, educational, and mathematical simulations.
Advantages of Canvas
Canvas provides important benefits for applications that require dynamic pixel-based graphics.
Game Rendering
Well suited for dynamic 2D game scenes.
Frequent Redrawing
Designed for graphics that change repeatedly.
Many Visual Objects
Can efficiently draw large numbers of simple objects.
Pixel Access
Applications can read and modify pixel data.
Animation
Supports frame-by-frame animation workflows.
Image Manipulation
Images can be drawn, cropped, scaled, and processed.
Single Drawing Surface
Complex scenes do not require thousands of DOM nodes.
Flexible API
JavaScript controls every stage of the drawing process.
Performance Advantages
- Efficient dynamic redrawing.
- No DOM node for every painted object.
- Suitable for many moving objects.
- Direct pixel manipulation.
Development Advantages
- Flexible drawing API.
- JavaScript-controlled rendering.
- Supports custom graphics engines.
- Works with images and video frames.
Canvas is especially useful when the application controls and redraws a visual scene continuously.
Common Beginner Mistakes
The <canvas> element creates only a blank surface. JavaScript must perform the drawing.
Drawing methods belong to the drawing context, not directly to the canvas element.
JavaScript cannot select a canvas that has not yet been created in the DOM.
Canvas paints pixels, while SVG represents graphics as vector elements.
CSS resizing can stretch the rendered bitmap and create blurry graphics.
New paths can accidentally connect to previous paths if beginPath() is omitted.
Creating a path does not automatically make it visible.
Images must be available before drawImage() can render them.
Old frames can remain visible and create unwanted trails.
Styles and transformations remain active until they are changed or restored.
Incorrect scaling can make canvas graphics blurry on high-density displays.
Canvas does not automatically provide a separate element for every object drawn.
Important information displayed only through canvas can be difficult for assistive technologies to understand.
Unnecessary calculations can reduce animation performance.
<!-- ❌ Only creates a blank canvas -->
<canvas
width="400"
height="300"
>
</canvas>
<!-- ✅ Canvas with JavaScript drawing -->
<canvas
id="myCanvas"
width="400"
height="300"
>
</canvas>
<script>
const canvas =
document.getElementById("myCanvas");
const ctx =
canvas.getContext("2d");
ctx.fillRect(
0,
0,
100,
100
);
</script>Poor Canvas Usage
- Expecting automatic graphics.
- Using CSS-only dimensions.
- Ignoring image loading.
- No animation frame management.
- No accessibility alternative.
Better Canvas Usage
- Use JavaScript drawing commands.
- Set proper internal resolution.
- Wait for resources to load.
- Manage animation efficiently.
- Provide accessible alternatives.
Best Practices
- Use Canvas for games, dynamic animations, image processing, and frequently changing visualizations.
- Use SVG for logos, icons, diagrams, and graphics that require scalable vector elements.
- Choose the rendering technology according to the application requirements.
- Give each important canvas a meaningful id.
- Set width and height attributes on the <canvas> element.
- Understand the difference between internal canvas resolution and CSS display size.
- Avoid resizing the canvas only through CSS.
- Scale the internal resolution appropriately for high-density displays.
- Test graphics on standard and high-DPI screens.
- Select the canvas only after it exists in the DOM.
- Store the canvas reference in a meaningful variable.
- Store the drawing context in a meaningful variable such as ctx.
- Check whether getContext() returned a valid context when appropriate.
- Use the 2D context for standard two-dimensional drawing.
- Learn the coordinate system before drawing complex scenes.
- Remember that the origin begins at the top-left.
- Remember that positive X values move right.
- Remember that positive Y values move down.
- Use fillStyle before drawing filled shapes.
- Use strokeStyle before drawing outlines.
- Use lineWidth to control line thickness.
- Use beginPath() when starting an independent path.
- Use moveTo() to position the path cursor.
- Use lineTo() to create straight path segments.
- Use arc() for circles and curved paths.
- Call stroke() to render path outlines.
- Call fill() to render filled paths.
- Use fillRect() for filled rectangles.
- Use strokeRect() for outlined rectangles.
- Use clearRect() when part of the canvas must be cleared.
- Configure ctx.font before drawing text.
- Use fillText() for filled text.
- Use strokeText() for outlined text.
- Wait for images to load before calling drawImage().
- Handle image loading errors when images are important.
- Use drawImage() dimensions carefully to preserve the intended aspect ratio.
- Avoid repeatedly loading the same image during animation.
- Preload reusable game and animation assets.
- Organize drawing code into reusable functions.
- Separate application state from rendering code.
- Create functions for drawing repeated objects.
- Avoid placing all drawing logic inside one enormous function.
- Use descriptive names for coordinates and dimensions.
- Use constants for values that should not change.
- Use arrays or objects to manage multiple visual entities.
- Store object positions separately from the rendered pixels.
- Remember that Canvas does not automatically remember drawn objects.
- Redraw objects when their state changes.
- Clear previous frames when required.
- Use requestAnimationFrame() for browser animations.
- Avoid setInterval() for high-quality visual animation when requestAnimationFrame() is more appropriate.
- Update application state before drawing the next frame.
- Keep the animation loop focused.
- Avoid unnecessary object creation inside every animation frame.
- Avoid expensive DOM operations inside animation loops.
- Avoid repeated calculations that can be cached.
- Measure performance before attempting complex optimization.
- Pause animations when they are not needed.
- Consider document visibility when running expensive animations.
- Use save() before temporary context changes.
- Use restore() after temporary context changes.
- Use translate(), rotate(), and scale() carefully.
- Remember that transformations affect future drawing commands.
- Reset or restore transformations when required.
- Use logical coordinate systems for complex scenes.
- Keep drawing order intentional.
- Draw backgrounds before foreground objects.
- Remember that later drawing commands can cover earlier pixels.
- Use offscreen rendering when advanced performance requirements justify it.
- Avoid redrawing unchanged areas when selective rendering is practical.
- Use clipping carefully.
- Keep image data operations limited because pixel processing can be expensive.
- Use getImageData() only when direct pixel access is required.
- Use putImageData() carefully for large images.
- Understand browser security restrictions when drawing cross-origin images.
- Use properly configured image sources when pixel access is required.
- Do not assume every externally loaded image can be read back safely.
- Handle responsive resizing deliberately.
- Recalculate object positions when canvas dimensions change.
- Redraw the scene after resizing.
- Preserve aspect ratio when required.
- Avoid stretching the bitmap accidentally.
- Provide fallback content inside the <canvas> element.
- Provide accessible text alternatives for meaningful visual content.
- Do not communicate essential information only through canvas.
- Provide equivalent HTML data for important charts when necessary.
- Provide keyboard alternatives for interactive canvas applications.
- Use visible focus indicators for interactive controls around canvas.
- Do not rely only on color to communicate state.
- Use sufficient visual contrast.
- Make interactive targets large enough to use.
- Provide instructions for complex interactive canvas experiences.
- Use semantic HTML around the canvas.
- Keep controls outside the canvas when normal HTML controls are more accessible.
- Use buttons for actions instead of drawing fake buttons when possible.
- Test with keyboard navigation.
- Test responsive behavior.
- Test touch interaction on mobile devices.
- Test pointer coordinates after CSS scaling.
- Convert mouse or touch coordinates correctly into canvas coordinates.
- Use devicePixelRatio carefully for sharp rendering.
- Avoid excessive canvas dimensions that consume large amounts of memory.
- Avoid unnecessarily large offscreen buffers.
- Clean up event listeners when canvas components are removed.
- Stop animation loops when components are destroyed.
- Release references to large images and buffers when no longer required.
- Use Canvas when its immediate-mode rendering model matches the application.
- Do not choose Canvas simply because the application contains graphics.
- Use SVG when individual graphical elements need easy DOM interaction.
- Use normal HTML when the content is primarily text and interface controls.
- Consider WebGL for advanced high-performance 3D rendering.
- Keep rendering code maintainable.
- Document complex coordinate calculations.
- Test performance on slower devices.
- Always balance visual quality, accessibility, responsiveness, maintainability, and performance.
function update() {
// Update positions,
// physics,
// game state,
// or animation values.
}
function draw() {
ctx.clearRect(
0,
0,
canvas.width,
canvas.height
);
// Draw the current scene.
}
function animate() {
update();
draw();
requestAnimationFrame(animate);
}
animate();Keeping application state updates separate from rendering makes games and animations easier to understand and maintain.
Frequently Asked Questions
What is HTML Canvas?
Canvas is a pixel-based drawing surface created using the <canvas> element and controlled primarily through JavaScript.
Which HTML element creates a canvas?
The <canvas> element.
Does Canvas draw graphics automatically?
No. The element creates a blank surface, and JavaScript performs the drawing.
Which language is normally used to draw on Canvas?
JavaScript.
How do I select a canvas?
You can select it using a DOM method such as document.getElementById().
What is a drawing context?
A drawing context is an object that provides the methods and properties used to draw on the canvas.
How do I get a 2D drawing context?
Call canvas.getContext("2d").
Where does the Canvas coordinate system begin?
At the top-left corner at coordinate (0,0).
Which direction does positive X move?
Toward the right.
Which direction does positive Y move?
Downward.
How do I draw a filled rectangle?
Use the fillRect() method.
How do I draw an outlined rectangle?
Use the strokeRect() method.
How do I clear part of a canvas?
Use the clearRect() method.
How do I draw a line?
Create a path using beginPath(), moveTo(), lineTo(), and stroke().
Why should I use beginPath()?
It starts a new path so new drawing commands do not unintentionally continue previous paths.
How do I draw a circle?
Use beginPath(), arc(), and then stroke() or fill().
What does 2 * Math.PI represent?
It represents a complete circle in radians.
How do I draw text?
Configure ctx.font and use fillText() or strokeText().
How do I draw an image?
Load the image and call drawImage() after the image is ready.
Why is my image not appearing?
The drawing code may be running before the image has finished loading.
Is Canvas vector-based?
No. The rendered Canvas surface is pixel-based.
Is SVG vector-based?
Yes.
Which is better for logos?
SVG is normally better because vector graphics scale without losing sharpness.
Which is better for browser games?
Canvas is often a strong choice for dynamic 2D game scenes, although the correct technology depends on the game requirements.
Can Canvas create animations?
Yes. Applications can repeatedly update and redraw the canvas.
Which method should be used for browser animation?
requestAnimationFrame() is normally the preferred browser animation mechanism.
Does Canvas remember each shape?
No. Applications normally store object state separately and redraw the scene when changes are required.
Can I click an individual Canvas shape?
Not automatically. The application usually performs coordinate-based hit detection.
Why does my Canvas look blurry?
The internal canvas resolution may not match its displayed CSS size or the device pixel density.
What is the difference between Canvas width attributes and CSS width?
The attributes define the internal drawing resolution, while CSS controls the displayed size.
Can Canvas manipulate pixels?
Yes. The 2D API provides methods for reading and writing image data.
Can Canvas process images?
Yes. Images can be drawn, cropped, scaled, filtered, and manipulated.
Can Canvas display video frames?
Yes. Video frames can be drawn onto a canvas.
Is Canvas accessible by default?
Canvas graphics require additional accessibility planning because the painted pixels do not automatically provide semantic structure.
Should interface buttons be drawn inside Canvas?
Normal HTML buttons are often preferable when standard accessible controls can satisfy the requirement.
Can Canvas create 3D graphics?
The basic 2D context is for two-dimensional graphics. Technologies such as WebGL are used for advanced 3D rendering.
What should I learn after HTML Canvas?
The next lesson is HTML Meta Tags.
Key Takeaways
- The <canvas> element creates a drawing surface.
- Canvas is blank until drawing commands are executed.
- JavaScript is normally used to draw on Canvas.
- Canvas uses a pixel-based rendering model.
- The canvas element should have appropriate width and height attributes.
- The id attribute allows JavaScript to select the canvas.
- The 2D drawing context is obtained using getContext("2d").
- The drawing context provides methods and properties for rendering graphics.
- Canvas uses an X-Y coordinate system.
- The default origin is the top-left corner.
- The origin coordinate is (0,0).
- Positive X values move toward the right.
- Positive Y values move downward.
- fillStyle controls the color of filled graphics.
- strokeStyle controls outline colors.
- lineWidth controls outline thickness.
- fillRect() draws filled rectangles.
- strokeRect() draws outlined rectangles.
- clearRect() clears rectangular regions.
- Paths begin with beginPath().
- moveTo() sets a path starting position.
- lineTo() creates a line toward another coordinate.
- stroke() draws path outlines.
- fill() fills path interiors.
- arc() creates circles and curved paths.
- A full circle can use an ending angle of 2 * Math.PI.
- ctx.font controls text font settings.
- fillText() draws filled text.
- strokeText() draws outlined text.
- drawImage() draws images onto Canvas.
- Images should finish loading before they are drawn.
- Canvas drawing commands execute in order.
- Later drawing commands can cover earlier pixels.
- Canvas does not automatically preserve drawn objects as DOM elements.
- Applications should store object state separately.
- Dynamic scenes are usually cleared and redrawn.
- requestAnimationFrame() is commonly used for animation loops.
- Canvas is useful for browser games.
- Canvas is useful for particle systems.
- Canvas is useful for drawing applications.
- Canvas is useful for image manipulation.
- Canvas is useful for frequently changing visualizations.
- SVG is usually better for scalable logos and icons.
- Canvas and SVG use different rendering models.
- Canvas requires additional planning for accessibility.
- Internal resolution and CSS display size should be managed carefully.
- High-density screens may require resolution scaling.
- Canvas is one of the most important browser technologies for dynamic graphics.
Summary
The HTML <canvas> element provides a blank pixel-based drawing surface that JavaScript can control.
Unlike SVG, Canvas does not represent every drawn shape as a separate vector element in the DOM.
JavaScript selects the canvas, obtains a drawing context, configures drawing styles, and executes commands that paint pixels onto the surface.
The 2D drawing context is created using getContext("2d").
Canvas uses a coordinate system that begins at the top-left corner, where positive X values move right and positive Y values move downward.
Rectangles can be created using fillRect() and strokeRect(), while clearRect() removes pixels from rectangular regions.
Lines and complex shapes are created using paths with methods such as beginPath(), moveTo(), lineTo(), stroke(), and fill().
Circles can be created using the arc() method, while text can be drawn using fillText() and strokeText().
Images can be rendered using drawImage(), but applications should wait until image resources have loaded.
Canvas drawing commands execute in sequence, and later commands can paint over earlier graphics.
Because Canvas does not automatically remember individual painted objects, applications normally maintain object state separately.
Games and animations commonly update application state, clear the previous frame, redraw the scene, and repeat the process using requestAnimationFrame().
Canvas is particularly useful for browser games, particle systems, drawing applications, image processing, simulations, and frequently changing visualizations.
SVG remains a better choice for many logos, icons, diagrams, and graphics that require individually accessible vector elements.
Developers should choose Canvas or SVG according to performance requirements, scalability, interaction, accessibility, and the type of graphics being created.
By understanding the drawing context, coordinate system, paths, shapes, images, animation workflow, resolution, and accessibility requirements, developers can create powerful dynamic graphics directly inside the browser.
In the next lesson, you will learn about HTML Meta Tags and how metadata provides important information about a webpage to browsers, search engines, and social platforms.