5 min read
ā¢Question 18 of 49mediumWhat is the Canvas Element?
Drawing graphics with JavaScript.
What You'll Learn
- What canvas element does
- How to draw shapes and text
- Common use cases
Understanding Canvas
The <canvas> element provides a drawing surface for JavaScript graphics. It's a bitmap canvas where you draw shapes, images, and animations programmatically.
Use Cases
- Games
- Data visualizations
- Image editing
- Real-time graphics
- Animations
Getting Started
index.htmlHTML
<canvas id="myCanvas" width="400" height="300"></canvas>code.jsJavaScript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 80);
// Draw circle
ctx.beginPath();
ctx.arc(200, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
// Draw text
ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas!', 100, 250);Context Types
- 2D:
getContext('2d')- shapes, text, images - WebGL:
getContext('webgl')- 3D graphics