HTML '<canvas>' Element

πŸ–ΌοΈ Introduction to HTML Canvas

The HTML <canvas> element is a powerful feature that allows developers to draw graphics directly in the browser using JavaScript. It can be used to render shapes, images, animations, games, and data visualizations. Think of it as a blank drawing board within your webpage. 🧠

>>β€œCanvas turns code into visual creativity.” β€” A Developer's Paintbrush πŸ–ŒοΈ

πŸ“Œ Syntax of the <canvas> Element

Basic Canvas Syntax

<canvas id="myCanvas" width="300" height="150">
  Your browser does not support the HTML canvas tag.
</canvas>

Note

πŸ’‘ Always provide fallback content inside the <canvas> tag for older browsers.

βš™οΈ Accessing the Canvas with JavaScript

To draw on the canvas, you need to get its rendering context using JavaScript. The most common context is "2d", used for 2D graphics.

Get 2D Context

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

✏️ Drawing Basics

πŸŸ₯ Drawing a Rectangle

Draw Filled and Stroked Rectangles

// Filled rectangle
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);

// Stroked rectangle
ctx.strokeStyle = "blue";
ctx.strokeRect(10, 70, 100, 50);
🟠 Drawing a Circle (Arc)

Draw a Circle

ctx.beginPath();
ctx.arc(75, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "green";
ctx.fill();
✍️ Drawing Text

Draw Text on Canvas

ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Canvas!", 10, 130);

πŸ’Ύ Embedding an Image

You can draw images onto the canvas using the drawImage() method.

Draw an Image

const img = new Image();
img.onload = function () {
  ctx.drawImage(img, 0, 0);
};
img.src = "image.jpg";

Note

⚠️ The image must be fully loaded before drawing or it won't render properly.

πŸ”„ Animation with requestAnimationFrame

To create animations, you can use requestAnimationFrame() to repeatedly update the canvas.

Simple Animation

let x = 0;
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(x, 30, 50, 50);
  x += 2;
  requestAnimationFrame(animate);
}
animate();

🧰 Canvas Use Cases

  • πŸ•ΉοΈ Game Development (e.g., Pong, Snake, Flappy Bird)
  • πŸ“Š Data Visualizations (e.g., bar charts, line graphs)
  • πŸ–ŒοΈ Drawing Tools (e.g., paint apps)
  • 🌌 Image Editing & Effects
  • πŸ§ͺ Simulations and interactive art

πŸ”— Useful Resources

>>β€œCode your imagination. Draw the impossible with <canvas>.” 🎨