Canvas in HTML
? <canvas> in HTML — Draw Graphics with Code
The <canvas> element in HTML5 lets you draw graphics, such as shapes, charts, games, and animations — all via JavaScript.
? Basic Syntax
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000000;"> Your browser does not support the canvas element.</canvas>id: Used to access the canvas in JavaScriptwidthandheight: Sets the drawing area sizeFallback text (inside the tag) appears if the browser doesn't support canvas
? How It Works
The <canvas> tag creates a blank space. You then use JavaScript to draw on it.
?? Drawing with JavaScript
Step 1: Get the Canvas and Context
<script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // 2D rendering context</script>? Example 1: Draw a Rectangle
<script> ctx.fillStyle = "green"; ctx.fillRect(10, 10, 150, 75); // x, y, width, height</script>? Example 2: Draw a Circle
<script> ctx.beginPath(); ctx.arc(100, 75, 50, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle ctx.stroke();</script>?? Example 3: Draw Text
<script> ctx.font = "30px Arial"; ctx.fillText("Hello Canvas", 50, 50);</script>? Example 4: Draw a Line
<script> ctx.moveTo(0, 0); // Start point ctx.lineTo(200, 100); // End point ctx.stroke();</script>? Canvas Methods Overview
| Method | Description |
|---|---|
fillRect() | Draws filled rectangle |
strokeRect() | Draws rectangle outline |
clearRect() | Clears part of the canvas |
beginPath() | Starts a new path |
moveTo(x, y) | Moves the pen to coordinates |
lineTo(x, y) | Draws a line |
arc() | Draws a circle or arc |
fillText(text, x, y) | Draws filled text |
strokeText(text, x, y) | Outlined text |
? What Can You Build with <canvas>?
Games (like Pong, Snake, Tetris)
Data visualizations and charts
Image editing tools
Custom animations
Interactive diagrams
? Tip:
Always check if getContext('2d') is available:
if (canvas.getContext) { const ctx = canvas.getContext('2d'); // Draw here} else { alert('Canvas is not supported in your browser.');}Would you like a mini canvas game, a drawing app, or a chart example using <canvas>?