11
The HTML5 <canvas> element provides a powerful way to draw and manipulate 2D shapes and images directly in the browser using JavaScript. It allows you to create dynamic graphics, such as charts, games, and visualizations.
In this tutorial, you’ll learn:
- Setting up the Canvas.
- Drawing basic shapes like rectangles, circles, and lines.
- Combining shapes to create more complex designs.
- Practical examples of 2D shape rendering.
1. Setting Up the Canvas
The <canvas> element is a container for graphics that you can draw using JavaScript.
Example: Basic Canvas Setup
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Setup</title> </head> <body> <h1>HTML5 Canvas</h1> <canvas id="myCanvas" width="500" height="400" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // Get the 2D rendering context </script> </body> </html>
2. Drawing Basic Shapes
2.1 Drawing Rectangles
Example: Filled and Stroked Rectangles
// Draw a filled rectangle ctx.fillStyle = "blue"; // Fill color ctx.fillRect(50, 50, 150, 100); // (x, y, width, height) // Draw a rectangle outline ctx.strokeStyle = "red"; // Outline color ctx.lineWidth = 3; // Outline thickness ctx.strokeRect(250, 50, 150, 100); // (x, y, width, height)
2.2 Drawing Circles (Arcs)
Example: Drawing Circles
// Draw a filled circle ctx.beginPath(); ctx.arc(150, 250, 50, 0, Math.PI * 2); // (x, y, radius, startAngle, endAngle) ctx.fillStyle = "green"; ctx.fill(); // Draw a circle outline ctx.beginPath(); ctx.arc(350, 250, 50, 0, Math.PI * 2); ctx.strokeStyle = "orange"; ctx.lineWidth = 4; ctx.stroke();
2.3 Drawing Lines
Example: Straight Lines
ctx.beginPath(); ctx.moveTo(50, 350); // Starting point ctx.lineTo(200, 350); // Ending point ctx.strokeStyle = "purple"; ctx.lineWidth = 2; ctx.stroke();
3. Combining Shapes
You can combine shapes to create more complex drawings.
Example: Drawing a House
// Draw the house body (rectangle) ctx.fillStyle = "brown"; ctx.fillRect(100, 200, 200, 150); // Draw the roof (triangle) ctx.beginPath(); ctx.moveTo(100, 200); // Left point ctx.lineTo(200, 100); // Top point ctx.lineTo(300, 200); // Right point ctx.closePath(); ctx.fillStyle = "red"; ctx.fill(); // Draw a door (rectangle) ctx.fillStyle = "black"; ctx.fillRect(180, 280, 40, 70);
4. Advanced Shapes
4.1 Drawing Polygons
Example: Drawing a Star
function drawStar(cx, cy, spikes, outerRadius, innerRadius) { const step = Math.PI / spikes; let rotation = -Math.PI / 2; ctx.beginPath(); for (let i = 0; i < spikes * 2; i++) { const radius = i % 2 === 0 ? outerRadius : innerRadius; const x = cx + Math.cos(rotation) * radius; const y = cy + Math.sin(rotation) * radius; ctx.lineTo(x, y); rotation += step; } ctx.closePath(); ctx.fillStyle = "gold"; ctx.fill(); ctx.strokeStyle = "black"; ctx.stroke(); } drawStar(250, 150, 5, 60, 30);
4.2 Drawing Bezier Curves
Example: Quadratic and Cubic Bezier Curves
// Quadratic Bezier Curve ctx.beginPath(); ctx.moveTo(50, 50); // Start point ctx.quadraticCurveTo(150, 150, 250, 50); // Control point and end point ctx.strokeStyle = "blue"; ctx.stroke(); // Cubic Bezier Curve ctx.beginPath(); ctx.moveTo(300, 50); // Start point ctx.bezierCurveTo(350, 200, 450, 0, 500, 50); // Two control points and end point ctx.strokeStyle = "green"; ctx.stroke();
5. Adding Text
Example: Drawing Text
// Filled Text ctx.font = "24px Arial"; ctx.fillStyle = "black"; ctx.fillText("Hello Canvas!", 50, 100); // Stroked Text ctx.strokeStyle = "red"; ctx.lineWidth = 1; ctx.strokeText("Outline Text", 50, 150);
6. Practical Example: Simple Face
Example: Drawing a Smiley Face
// Draw the face (circle) ctx.beginPath(); ctx.arc(250, 250, 100, 0, Math.PI * 2); ctx.fillStyle = "yellow"; ctx.fill(); ctx.strokeStyle = "black"; ctx.stroke(); // Draw the left eye ctx.beginPath(); ctx.arc(210, 220, 10, 0, Math.PI * 2); ctx.fillStyle = "black"; ctx.fill(); // Draw the right eye ctx.beginPath(); ctx.arc(290, 220, 10, 0, Math.PI * 2); ctx.fillStyle = "black"; ctx.fill(); // Draw the mouth (arc) ctx.beginPath(); ctx.arc(250, 250, 50, 0, Math.PI); ctx.strokeStyle = "black"; ctx.lineWidth = 3; ctx.stroke();
7. Best Practices
- Use beginPath for Separate Shapes:
- Always call beginPath before starting a new shape to prevent unwanted connections.
- Set Context Properties Thoughtfully:
- Properties like fillStyle and strokeStyle persist across drawings. Reset them as needed.
- Layer Shapes Correctly:
- Draw background shapes first and foreground shapes later.
8. Full Example: Canvas Art
Example: Drawing a Scene
// Sky ctx.fillStyle = "lightblue"; ctx.fillRect(0, 0, 500, 400); // Sun ctx.beginPath(); ctx.arc(400, 80, 50, 0, Math.PI * 2); ctx.fillStyle = "yellow"; ctx.fill(); // Ground ctx.fillStyle = "green"; ctx.fillRect(0, 300, 500, 100); // House ctx.fillStyle = "brown"; ctx.fillRect(150, 200, 200, 100); // Roof ctx.beginPath(); ctx.moveTo(150, 200); ctx.lineTo(250, 150); ctx.lineTo(350, 200); ctx.closePath(); ctx.fillStyle = "red"; ctx.fill(); // Tree ctx.fillStyle = "brown"; ctx.fillRect(50, 230, 20, 70); ctx.beginPath(); ctx.arc(60, 230, 40, 0, Math.PI * 2); ctx.fillStyle = "darkgreen"; ctx.fill();
9. Browser Support
HTML5 Canvas is supported by all modern browsers:
Browser | Supported? |
---|---|
Google Chrome | Yes |
Firefox | Yes |
Safari | Yes |
Microsoft Edge | Yes |
Internet Explorer | Yes (IE9+) |
10. Conclusion
In this tutorial, you learned:
- How to set up the <canvas> element.
- How to draw basic 2D shapes (rectangles, circles, lines).
- How to create complex shapes like polygons and curves.
- Practical examples for creating drawings like a house or a face.
The HTML5 Canvas API provides extensive tools for creating custom graphics and visualizations.