HTML Canvas Graphics

HTML Canvas Graphics
It is powerful for creating shapes, charts, games, animations, and visual effects directly in the browser.
1. What Is HTML Canvas?
<canvas>is a bitmap drawing areaGraphics are drawn using JavaScript
Used for 2D graphics (and with libraries, 3D too)
No drawing by itself → JS is required
2. Basic Canvas Setup
HTML
JavaScript
getContext("2d")gives the drawing tool
3. Drawing a Line
moveTo()→ starting pointlineTo()→ ending pointstroke()→ draws the line
4. Drawing a Rectangle
Stroke Rectangle
Filled Rectangle
5. Drawing a Circle (Arc)
arc(x, y, radius, startAngle, endAngle)
6. Drawing Text
Fill Text
Stroke Text
7. Adding Colors & Styles
8. Drawing an Image
- Used for games & graphics
9. Canvas Coordinates System
Top-left corner =
(0, 0)X-axis → right
Y-axis → down
All drawing is based on this coordinate system.
10. Simple Animation (Basic Example)
- Smooth animation
- Used in games & motion graphics
11. Canvas vs SVG (Quick Comparison)
| Feature | Canvas | SVG |
|---|---|---|
| Rendering | Bitmap | Vector |
| Scalability | No | Yes |
| Performance | High | Medium |
| Animations | JS-based | CSS/SMIL |
| Best for | Games, charts | Icons, diagrams |
Common Mistakes
- Forgetting to set
width&height Trying to draw without JavaScript- Not clearing canvas in animations
- Expecting canvas content to be accessible by default
Key Points to Remember
<canvas>is drawn using JavaScriptUses a coordinate system
Perfect for graphics & games
Needs manual redraw
High performance rendering
