Tag canvas

The <canvas> tag is an HTML element used to draw graphics such as 2D shapesimages, and animations directly in the browser, using JavaScript.

Think of it like a digital drawing board where you can create anything from simple lines to complex graphics, games, and even interactive visuals.


✅ Basic Syntax

<canvas id="myCanvas" width="400" height="200"></canvas>
  • id — assigns an identifier to the canvas for JavaScript manipulation.
  • width and height — set the dimensions of the canvas (in pixels).

If you don’t set these attributes, the default size will be 300px by 150px.


🧑‍💻 Drawing on the Canvas (JavaScript Example)

Once the canvas is in place, we can use JavaScript to draw graphics on it.

<canvas id="myCanvas" width="400" height="200"></canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d"); // 2D context for drawing

// Draw a blue rectangle
ctx.fillStyle = "#0000FF";
ctx.fillRect(50, 50, 150, 100); // (x, y, width, height)
</script>

This script creates a blue rectangle on the canvas.


🎨 More Canvas Drawing Examples

1. Draw a Circle

script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// Draw a red circle
ctx.beginPath();
ctx.arc(200, 100, 50, 0, 2 * Math.PI); // (x, y, radius, startAngle, endAngle)
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();
</script>

2. Draw a Line

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// Draw a green line
ctx.beginPath();
ctx.moveTo(50, 50); // Starting point
ctx.lineTo(350, 150); // Ending point
ctx.strokeStyle = "green";
ctx.lineWidth = 3;
ctx.stroke();
</script>

🏎️ Advanced Use Cases

  1. Animations
    The canvas can be used to create animations by repeatedly redrawing graphics with JavaScript’s requestAnimationFrame().
  2. Game Development
    Popular for creating 2D games — you can control movement, collisions, and rendering of dynamic scenes.
  3. Data Visualization
    You can use libraries like Chart.js to draw interactive graphs and charts on the canvas.

🚀 Performance and Browser Support

  • Fast Rendering: The <canvas> element is hardware accelerated in most browsers, making it suitable for high-performance graphics.
  • Cross-browser support: Works in modern browsers like Chrome, Firefox, Safari, and Edge.
  • Mobile: Supported on mobile browsers, so you can create interactive mobile graphics.

✅ Summary

FeatureDetails
PurposeDraw graphics, animations, games
JavaScript APIgetContext("2d") for 2D graphics
DimensionsUse width and height attributes
PerformanceHardware accelerated in modern browsers
Use casesGames, data visualization, animations