<canvas> Tag in HTML
The <canvas> tag is used to draw graphics on a web page using JavaScript. It allows you to draw shapes, images, and other graphical elements on the fly. The canvas element is often used for creating dynamic graphics, such as charts, graphs, animations, and game graphics.
Key Points on <canvas> Tag:
- The <canvas> tag provides an area to draw graphics via JavaScript.
- It does not provide any visual output by itself; it needs JavaScript to draw on it.
- The canvas size can be defined using width and height attributes.
- Commonly used for creating interactive graphics, games, and real-time visualizations.
Syntax of <canvas> Tag:
Syntax Example
<canvas width="200" height="200"></canvas>
Example of <canvas> Tag in HTML:
This example demonstrates how to create a basic canvas and draw a rectangle on it using JavaScript.
Code Example
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(20, 20, 150, 100);
</script>
Output
Canvas Attributes:
- width – Specifies the width of the canvas.
- height – Specifies the height of the canvas.
Canvas Methods:
- getContext("2d") – Returns a drawing context on the canvas for 2D rendering.
- fillRect(x, y, width, height) – Draws a filled rectangle at the specified coordinates.
- beginPath() – Starts a new path for drawing.
- moveTo(x, y) – Moves the pen to the specified coordinates.
- lineTo(x, y) – Draws a line to the specified coordinates.
- stroke() – Renders the current path using the stroke style.
- clearRect(x, y, width, height) – Clears the specified rectangular area on the canvas.
The <canvas> tag is extremely powerful for creating complex graphics, animations, and games directly in the browser. By using JavaScript, you can manipulate pixels and create dynamic, interactive content that responds to user input.