The <canvas>
element in HTML provides a way to draw graphics on a web page using JavaScript. It acts as a blank drawing surface where you can render shapes, images, and animations dynamically. It's a powerful tool for creating interactive visualizations and games directly in the browser.
Example 1: Basic Canvas Setup
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
Explanation This code defines a <canvas>
element with a unique ID, specified dimensions, and a border for visibility. The content inside the tags is displayed only if the user's browser doesn't support canvas, providing graceful degradation.
Example 2: Drawing a Rectangle
<canvas id="rectCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
<script>
const canvas = document.getElementById('rectCanvas');
const ctx = canvas.getContext('2d'); // Get the 2D rendering context
ctx.fillStyle = "#FF0000"; // Set fill color to red
ctx.fillRect(20, 20, 150, 75); // Draw a filled rectangle (x, y, width, height)
</script>
Explanation This example retrieves the 2D rendering context of the canvas. It then sets the fill style to red and draws a filled rectangle at specified coordinates and dimensions. This demonstrates a fundamental drawing operation.
Example 3: Drawing a Circle
<canvas id="circleCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
<script>
const canvas = document.getElementById('circleCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath(); // Start a new path
ctx.arc(95, 50, 40, 0, 2 * Math.PI); // Create a circular arc (x, y, radius, startAngle, endAngle)
ctx.strokeStyle = "#0000FF"; // Set stroke color to blue
ctx.stroke(); // Draw the stroke of the path
</script>
Explanation Here, a circular path is created using beginPath()
and arc()
. The strokeStyle
is set to blue, and stroke()
draws the outline of the circle. This illustrates how to draw more complex shapes on the canvas.