Introduction to HTML5 Canvas
The HTML5 <canvas>
element provides a dynamic surface for drawing graphics, animations, and interactive visuals using JavaScript. It’s widely used for games, data visualizations, and custom UI elements.
- Purpose: Create 2D graphics programmatically.
- Key Requirement: JavaScript to manipulate the canvas.
The <canvas>
Element
The <canvas>
element defines a rectangular drawing area. It requires width
and height
attributes (in pixels) and an id
for JavaScript access.
- Fallback Content: Text or elements inside
<canvas>
display if the browser doesn’t support it. - Default Size: 300×150 pixels if not specified.
Example: Basic canvas setup:
<canvas id="myCanvas" width="400" height="200">
Your browser does not support the canvas element.
</canvas>
Accessing the Canvas Context
JavaScript interacts with the canvas via its 2D rendering context, accessed using getContext('2d')
.
- Context Methods: Draw shapes, text, and images.
- Common Properties:
fillStyle
,strokeStyle
,lineWidth
.
Example: Drawing a rectangle:
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 80);
</script>
Drawing Basic Shapes
The canvas supports drawing lines, rectangles, circles, and paths.
- Rectangles:
fillRect(x, y, width, height)
,strokeRect()
,clearRect()
. - Paths: Use
beginPath()
,moveTo()
,lineTo()
,arc()
, andclosePath()
. - Circles: Draw using
arc(x, y, radius, startAngle, endAngle)
.
Example: Drawing a circle:
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
</script>
Adding Text and Images
- Text: Use
fillText(text, x, y)
orstrokeText()
. Customize withfont
,textAlign
. - Images: Draw images using
drawImage(img, x, y)
after loading an<img>
element.
Example: Adding text and an image:
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = '20px Arial';
ctx.fillText('Hello Canvas!', 50, 50);
const img = new Image();
img.src = 'logo.png';
img.onload = () => ctx.drawImage(img, 50, 80, 100, 100);
</script>
Animations on Canvas
Animations are created by repeatedly clearing and redrawing the canvas using JavaScript’s requestAnimationFrame()
.
- Steps: Clear canvas, update object positions, redraw.
- Performance: Use
requestAnimationFrame
for smooth animations.
Example: Simple moving rectangle:
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x += 2;
if (x > canvas.width) x = 0;
requestAnimationFrame(animate);
}
animate();
</script>
Best Practices for Canvas
- Set Dimensions: Always define
width
andheight
in HTML, not CSS, to avoid scaling issues. - Optimize Performance: Minimize redraws and use efficient JavaScript.
- Accessibility: Provide fallback content or alternative text descriptions.
- Test Compatibility: Ensure canvas works across modern browsers.
Example: Accessible canvas with fallback:
<canvas id="myCanvas" width="400" height="200">
<p>This animation requires a modern browser with canvas support.</p>
</canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(100, 100, 50, 50);
</script>
Leave a Reply