The HTML5 <canvas> element allows you to draw graphics on a webpage. It provides a powerful, low-level API for rendering 2D shapes, images, and animations.
In this tutorial, you’ll learn how to use the <canvas> element with examples covering drawing shapes, applying styles, handling animations, and more.
1. What is the <canvas> Element?
- The <canvas> element creates a rectangular area on your webpage where graphics can be drawn using JavaScript.
- It is resolution-dependent and does not provide any built-in drawing tools.
- You use the Canvas API to draw and manipulate the canvas content.
2. Basic Canvas Setup
Example 1: Basic Canvas Element
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Basic Canvas</title> </head> <body> <h1>Basic Canvas Example</h1> <canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas> </body> </html>
Explanation:
- <canvas>: Creates a canvas with a width of 500px and height of 300px.
- The canvas itself does not render any content. Use JavaScript to draw on it.
3. Drawing on the Canvas
You must obtain a 2D rendering context to draw on the canvas.
Example 2: Drawing a Rectangle
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Draw Rectangle</title> </head> <body> <h1>Canvas Rectangle</h1> <canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // Draw a filled rectangle ctx.fillStyle = "blue"; ctx.fillRect(50, 50, 150, 100); // Draw a rectangle outline ctx.strokeStyle = "red"; ctx.lineWidth = 5; ctx.strokeRect(250, 50, 150, 100); </script> </body> </html>
Explanation:
- ctx.fillRect(x, y, width, height): Draws a filled rectangle.
- ctx.strokeRect(x, y, width, height): Draws a rectangle outline.
- fillStyle and strokeStyle: Set the fill and stroke colors.
4. Drawing Shapes
The Canvas API supports paths for drawing shapes like circles, lines, and polygons.
Example 3: Drawing a Circle and Line
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Shapes</title> </head> <body> <h1>Canvas Shapes</h1> <canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // Draw a circle ctx.beginPath(); ctx.arc(150, 150, 50, 0, Math.PI * 2); ctx.fillStyle = "green"; ctx.fill(); // Draw a line ctx.beginPath(); ctx.moveTo(300, 100); ctx.lineTo(400, 200); ctx.strokeStyle = "blue"; ctx.lineWidth = 3; ctx.stroke(); </script> </body> </html>
Explanation:
- ctx.arc(x, y, radius, startAngle, endAngle): Draws a circle or arc.
- ctx.moveTo(x, y) and ctx.lineTo(x, y): Define a line segment.
5. Adding Text to the Canvas
You can render text on the canvas using the fillText and strokeText methods.
Example 4: Adding Text
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Text</title> </head> <body> <h1>Canvas Text Example</h1> <canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // Draw filled text ctx.font = "30px Arial"; ctx.fillStyle = "black"; ctx.fillText("Hello Canvas!", 50, 100); // Draw outlined text ctx.strokeStyle = "red"; ctx.strokeText("Outline Text", 50, 150); </script> </body> </html>
Explanation:
- ctx.font: Sets the font size and family.
- ctx.fillText(text, x, y): Renders filled text.
- ctx.strokeText(text, x, y): Renders text outlines.
6. Drawing Images
You can draw images onto the canvas using the drawImage method.
Example 5: Drawing an Image
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Image</title> </head> <body> <h1>Canvas Image Example</h1> <canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); const img = new Image(); img.src = "https://via.placeholder.com/150"; img.onload = () => { ctx.drawImage(img, 50, 50, 150, 150); // Draw the image at (50, 50) }; </script> </body> </html>
Explanation:
- ctx.drawImage(image, x, y, width, height): Draws an image onto the canvas.
- The onload event ensures the image is fully loaded before being drawn.
7. Animating on the Canvas
You can create animations by repeatedly drawing and clearing the canvas.
Example 6: Animation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Animation</title> </head> <body> <h1>Canvas Animation</h1> <canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); let x = 0; const y = 150; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas ctx.beginPath(); ctx.arc(x, y, 20, 0, Math.PI * 2); ctx.fillStyle = "blue"; ctx.fill(); x += 2; // Move the circle if (x > canvas.width) x = 0; // Reset if it goes off-screen requestAnimationFrame(draw); // Request the next frame } draw(); // Start the animation </script> </body> </html>
Explanation:
- clearRect: Clears the canvas before redrawing.
- requestAnimationFrame: Ensures smooth animations by syncing with the browser’s refresh rate.
8. Handling User Interaction
You can capture mouse events to make interactive graphics.
Example 7: Interactive Canvas
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Interactive Canvas</title> </head> <body> <h1>Interactive Canvas Example</h1> <canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); canvas.addEventListener("mousemove", (e) => { const rect = canvas.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.arc(x, y, 30, 0, Math.PI * 2); ctx.fillStyle = "blue"; ctx.fill(); }); </script> </body> </html>
Explanation:
- mousemove event: Tracks the mouse position on the canvas.
- getBoundingClientRect: Gets the canvas’s position relative to the viewport.
9. Best Practices
- Optimize for Performance: Clear and redraw only what is necessary.
- Responsive Design: Use CSS or JavaScript to make the canvas adapt to screen size.
- Backup Content: Provide fallback content inside the <canvas> tag for browsers that do not support it.
Conclusion
In this tutorial, you learned:
- How to create and use the <canvas> element.
- How to draw shapes, text, and images on the canvas.
- How to add interactivity and animations.
The Canvas API is a versatile tool for creating graphics, animations, and interactive content.