<canvas>
Used to draw graphics via JavaScript
✨ HTML5Definition and Usage
The <canvas> tag is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images. It's widely used for creating games, data visualizations, image editing applications, and animations.
<canvas> element has no drawing abilities of its own. All drawing must be done inside JavaScript using the Canvas API.
<canvas> tag for browsers that don't support it or when JavaScript is disabled.
Browser Support
The <canvas> tag is an HTML5 element and is supported in all modern browsers:
Attributes
| Attribute | Value | Description |
|---|---|---|
| width | pixels | Specifies the width of the canvas (default is 300) |
| height | pixels | Specifies the height of the canvas (default is 150) |
Global Attributes
The <canvas> tag also supports all HTML global attributes such as class, id, style, etc.
Examples
Basic Canvas
Creating a simple canvas element:
Example
<canvas id="myCanvas" width="400" height="200">
Your browser does not support the canvas element.
</canvas>
Drawing a Rectangle
Using JavaScript to draw a filled rectangle:
Example
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw a filled rectangle
ctx.fillStyle = '#764ba2';
ctx.fillRect(50, 50, 200, 100);
// Draw a stroked rectangle
ctx.strokeStyle = '#f093fb';
ctx.lineWidth = 3;
ctx.strokeRect(100, 80, 200, 100);
</script>
Drawing Shapes
Drawing circles and paths:
Example
<canvas id="shapesCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('shapesCanvas');
const ctx = canvas.getContext('2d');
// Draw a circle
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#4CAF50';
ctx.fill();
// Draw a triangle
ctx.beginPath();
ctx.moveTo(250, 50);
ctx.lineTo(200, 150);
ctx.lineTo(300, 150);
ctx.closePath();
ctx.fillStyle = '#f44336';
ctx.fill();
</script>
Drawing with Gradients
Creating linear and radial gradients:
Example
<canvas id="gradientCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('gradientCanvas');
const ctx = canvas.getContext('2d');
// Linear gradient
const linearGrad = ctx.createLinearGradient(0, 0, 200, 0);
linearGrad.addColorStop(0, '#764ba2');
linearGrad.addColorStop(1, '#f093fb');
ctx.fillStyle = linearGrad;
ctx.fillRect(20, 20, 200, 160);
// Radial gradient
const radialGrad = ctx.createRadialGradient(320, 100, 10, 320, 100, 80);
radialGrad.addColorStop(0, '#FFD700');
radialGrad.addColorStop(1, '#FF6347');
ctx.fillStyle = radialGrad;
ctx.fillRect(240, 20, 160, 160);
</script>
Drawing Text
Adding text to canvas:
Example
<canvas id="textCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('textCanvas');
const ctx = canvas.getContext('2d');
// Set text properties
ctx.font = '30px Arial';
ctx.fillStyle = '#764ba2';
ctx.fillText('Hello Canvas!', 50, 50);
// Stroked text
ctx.font = 'bold 40px Georgia';
ctx.strokeStyle = '#f093fb';
ctx.lineWidth = 2;
ctx.strokeText('HTML5', 50, 120);
</script>
Drawing Images
Rendering images on canvas:
Example
<canvas id="imageCanvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {
// Draw image
ctx.drawImage(img, 0, 0, 200, 150);
// Draw scaled image
ctx.drawImage(img, 210, 0, 180, 135);
// Draw cropped and positioned image
ctx.drawImage(img, 50, 50, 100, 100, 0, 160, 120, 120);
};
img.src = 'image.jpg';
</script>
Simple Animation
Creating animated graphics:
Example
<canvas id="animCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('animCanvas');
const ctx = canvas.getContext('2d');
let x = 0;
function animate() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw moving circle
ctx.beginPath();
ctx.arc(x, 100, 30, 0, 2 * Math.PI);
ctx.fillStyle = '#764ba2';
ctx.fill();
// Update position
x += 2;
if (x > canvas.width + 30) x = -30;
// Continue animation
requestAnimationFrame(animate);
}
animate();
</script>
Interactive Drawing
Creating a simple drawing application:
Example
<canvas id="drawCanvas" width="400" height="300"
style="border: 1px solid var(--border-color);"></canvas>
<script>
const canvas = document.getElementById('drawCanvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
});
canvas.addEventListener('mousemove', (e) => {
if (isDrawing) {
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = '#764ba2';
ctx.lineWidth = 2;
ctx.stroke();
}
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
</script>
Try it Yourself
Interactive Example
JavaScript Canvas API Basics
Key methods and properties of the Canvas API:
| Method/Property | Description |
|---|---|
| getContext('2d') | Returns a 2D drawing context on the canvas |
| fillRect(x, y, w, h) | Draws a filled rectangle |
| strokeRect(x, y, w, h) | Draws a rectangular outline |
| clearRect(x, y, w, h) | Clears the specified rectangular area |
| beginPath() | Begins a new path or resets the current path |
| moveTo(x, y) | Moves the path to the specified point |
| lineTo(x, y) | Adds a line to the path |
| arc(x, y, r, start, end) | Creates an arc/curve (used to create circles) |
| fill() | Fills the current path |
| stroke() | Draws the path |
| fillText(text, x, y) | Draws filled text |
| strokeText(text, x, y) | Draws text outline |
| drawImage(img, x, y) | Draws an image on the canvas |
Understanding getContext('2d')
The getContext() method returns a drawing context on the canvas. The context is the object that provides the methods and properties for drawing:
Example
// Get the canvas element
const canvas = document.getElementById('myCanvas');
// Get the 2D rendering context
const ctx = canvas.getContext('2d');
// Check if browser supports canvas
if (ctx) {
// Canvas is supported - draw something
ctx.fillStyle = '#764ba2';
ctx.fillRect(0, 0, 150, 75);
} else {
// Canvas is not supported
console.log('Canvas not supported');
}
Canvas vs SVG
Comparing Canvas with SVG for graphics:
| Feature | Canvas | SVG |
|---|---|---|
| Type | Raster-based (pixel-based) | Vector-based (shape-based) |
| Rendering | Rendered with JavaScript | Part of the DOM |
| Event Handling | Manual tracking required | Event handlers on each element |
| Performance | Better for many objects/animations | Better for few objects with interactivity |
| Scalability | Quality decreases when scaled | Scales perfectly at any size |
| Accessibility | Poor accessibility without extra work | Better accessibility support |
| Best For | Games, pixel manipulation, many objects | Interactive diagrams, charts, icons |
Use Cases
- Games: Canvas is perfect for creating 2D games with smooth animations and performance
- Data Visualization: Charts, graphs, and dashboards (libraries like Chart.js use Canvas)
- Image Editing: Photo filters, cropping tools, and image manipulation applications
- Drawing Applications: Sketching tools, whiteboard applications, signature capture
- Animations: Complex animations and visual effects
- Particle Systems: Snow effects, fireworks, and other particle-based animations
- Real-time Graphics: Video processing, webcam effects, real-time data displays
- Generative Art: Creating algorithmic and procedural artwork
Best Practices
- Set dimensions in HTML: Always use HTML attributes for width/height, not CSS
- Provide fallback content: Include text between canvas tags for unsupported browsers
- Cache canvas references: Store canvas and context references instead of querying repeatedly
- Use requestAnimationFrame: For animations, use
requestAnimationFrame()instead of setInterval - Clear before redrawing: Use
clearRect()to clear canvas before drawing new frames - Optimize drawing calls: Batch similar operations and minimize state changes
- Use offscreen canvas: For complex graphics, render to an offscreen canvas first
- Consider accessibility: Provide text alternatives and ARIA labels for canvas content
- Handle high DPI displays: Scale canvas for retina and high-DPI screens
Accessibility Considerations
- Fallback content: Always provide meaningful fallback content inside the canvas tag
- ARIA roles: Use
role="img"andaria-labelto describe canvas content - Text alternatives: Provide text descriptions of visual content for screen readers
- Keyboard support: Implement keyboard controls for interactive canvas applications
- Focus management: Ensure focus indicators are visible and logical
- Alternative formats: Consider providing data tables or text summaries for data visualizations
Example - Accessible Canvas
<canvas id="chart" width="400" height="300"
role="img"
aria-label="Bar chart showing sales data for Q1 2024">
Sales data for Q1 2024:
January: $50,000
February: $65,000
March: $72,000
</canvas>
HTML Free Codes