- HTML Programming Tutorial
- HTML - Home
- Basics of HTML
- Introduction to HTML
- Basic Structure of an HTML Document
- HTML Elements and Tags
- HTML Attributes
- HTML Comments
- HTML Syntax Rules
- Text and Structure
- Text Formatting Tags
- Text Alignment and Styling
- Block-level and Inline Elements in HTML
- Creating Lists in HTML
- Tables in HTML
- HTML Tables
- Images and Multimedia
- Images in HTML
- Multimedia in HTML
- Forms and Input
- HTML Forms
- Form Controls
- Advanced Elements
- HTML5 New Elements
- HTML5 Input Elements
- HTML5 Forms Enhancements
- CSS and Styling with HTML
- Inline Styles
- Embedded Styles (Internal CSS)
- External Stylesheets
- CSS Classes and IDs
- Responsive Web Design
- HTML Layouts
- HTML Layout Techniques
- Meta Tags and Viewport
- HTML5 APIs and Advanced Features
- HTML5 Web Storage
- Geolocation API
- Canvas Element
- Web Workers and Threads
- WebSockets
- Offline Web Applications
- Accessibility in HTML
- Accessible HTML Elements
- HTML Debugging and Optimization
- HTML Validation
- Performance Optimization in HTML
- HTML Best Practices
- Semantic HTML
- SEO and HTML
- Security Best Practices in Web Development
- Links and Navigation
- Hyperlinks in HTML
HTML Canvas Element
![]() Share with a Friend |
Introduction
The <canvas> element in HTML5 is a powerful tool for creating and manipulating 2D graphics directly in the browser. It is widely used for animations, charts, games, image manipulation, and more.
What is the <canvas> Element?
The <canvas> element provides a drawing area in HTML that allows developers to render graphics using JavaScript. It does not draw anything by itself; JavaScript is used to manipulate the drawing context.
- Tag: <canvas>
- Requires JavaScript: Yes, to draw or manipulate graphics.
Syntax of <canvas>
<canvas id="myCanvas" width="500" height="300"></canvas>
Attributes:
- width: Defines the width of the canvas in pixels (default is 300px).
- height: Defines the height of the canvas in pixels (default is 150px).
Content inside the <canvas> tag will only be displayed if the browser does not support the <canvas> element.
Example Fallback Content:
<canvas id="myCanvas" width="500" height="300"> Your browser does not support the canvas element. </canvas>
Getting Started with Canvas
To use the <canvas> element:
- Add the <canvas> tag in your HTML.
- Access its drawing context in JavaScript using getContext().
Example:
<canvas id="myCanvas" width="400" height="200"></canvas> <script> let canvas = document.getElementById("myCanvas"); let ctx = canvas.getContext("2d"); // Get 2D drawing context ctx.fillStyle = "blue"; // Set fill color ctx.fillRect(50, 50, 100, 100); // Draw a blue rectangle </script>
Drawing 2D Graphics
The canvas allows drawing various shapes and paths. Below are some common operations:
1. Drawing Rectangles
- fillRect(x, y, width, height): Draws a filled rectangle.
- strokeRect(x, y, width, height): Draws an outlined rectangle.
- clearRect(x, y, width, height): Clears a rectangular area.
Example:
ctx.fillStyle = "green"; // Set fill color ctx.fillRect(10, 10, 150, 100); // Filled rectangle ctx.strokeStyle = "red"; // Set border color ctx.lineWidth = 5; // Set border width ctx.strokeRect(200, 50, 100, 100); // Outlined rectangle ctx.clearRect(50, 50, 50, 50); // Clears a section inside the canvas
2. Drawing Paths
Paths are used to create shapes like lines, curves, and custom polygons.
Steps:
- Start a path: beginPath()
- Define the path: moveTo(x, y), lineTo(x, y)
- Draw the path: stroke() or fill()
Example: Drawing a Triangle
ctx.beginPath(); // Start a new path ctx.moveTo(75, 50); // Move to the starting point ctx.lineTo(100, 75); // Draw a line to (100, 75) ctx.lineTo(50, 75); // Draw a line to (50, 75) ctx.closePath(); // Close the path ctx.fillStyle = "yellow"; ctx.fill(); // Fill the triangle ctx.stroke(); // Outline the triangle
3. Drawing Circles and Arcs
arc(x, y, radius, startAngle, endAngle, anticlockwise):
- x, y: Center of the circle
- radius: Radius of the circle
- startAngle, endAngle: Angles in radians
- anticlockwise: Optional boolean to draw counterclockwise
Example:
ctx.beginPath(); ctx.arc(150, 75, 50, 0, 2 * Math.PI); // Circle ctx.fillStyle = "orange"; ctx.fill(); // Fill the circle ctx.stroke(); // Outline the circle
4. Drawing Text
- fillText(text, x, y): Draws filled text.
- strokeText(text, x, y): Draws outlined text.
Example:
ctx.font = "20px Arial"; // Set font style ctx.fillStyle = "blue"; ctx.fillText("Hello, Canvas!", 50, 50); ctx.strokeStyle = "black"; ctx.strokeText("Hello, Canvas!", 50, 80);
5. Adding Colors and Gradients
- Solid Colors:
- Use fillStyle or strokeStyle.
- Gradients:
- Linear Gradient: createLinearGradient(x0, y0, x1, y1)
- Radial Gradient: createRadialGradient(x0, y0, r0, x1, y1, r1)
Example: Linear Gradient:
let gradient = ctx.createLinearGradient(0, 0, 200, 0); gradient.addColorStop(0, "red"); gradient.addColorStop(1, "blue"); ctx.fillStyle = gradient; ctx.fillRect(10, 10, 200, 100); // Rectangle with gradient fill
6. Adding Images
drawImage(image, x, y, width, height):
- Draw an image onto the canvas.
Example:
let img = new Image(); img.src = "image.jpg"; // Image source img.onload = () => { ctx.drawImage(img, 50, 50, 200, 100); };
Use Cases of <canvas>
- Games:
- Canvas is widely used to develop 2D games.
- Data Visualization:
- Render charts, graphs, or dashboards.
- Image Editing:
- Manipulate and process images.
- Custom Animations:
- Create moving graphics or interactive elements.
- Creative Art:
- Tools like painting or drawing applications.
Browser Support
The <canvas> element is supported by all modern browsers, including:
- Google Chrome
- Mozilla Firefox
- Microsoft Edge
- Apple Safari
- Opera
Full Practical Example: Drawing Shapes
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas Example</title> </head> <body> <h1>HTML Canvas Example</h1> <canvas id="myCanvas" width="500" height="400" style="border:1px solid black;"></canvas> <script> let canvas = document.getElementById("myCanvas"); let ctx = canvas.getContext("2d"); // Draw a rectangle ctx.fillStyle = "blue"; ctx.fillRect(50, 50, 100, 100); // Draw a circle ctx.beginPath(); ctx.arc(300, 100, 50, 0, 2 * Math.PI); ctx.fillStyle = "red"; ctx.fill(); // Draw text ctx.font = "20px Arial"; ctx.fillStyle = "green"; ctx.fillText("Hello Canvas!", 150, 200); </script> </body> </html>
Conclusion
The <canvas> element provides endless possibilities for creating dynamic, interactive content directly in the browser.
