HTML Canvas

The <canvas> element in HTML allows graphics to be drawn using JavaScript. It provides a blank area on the page where custom drawings, shapes, animations, and even games can be created.

What is HTML Canvas?

The <canvas> tag creates a space on the web page that can be used for drawing graphics dynamically. Unlike SVG, Canvas is pixel-based and depends on JavaScript for all rendering.

Canvas Syntax

The canvas element must have a defined width and height. Everything drawn inside it is controlled via JavaScript.

<canvas id="myCanvas" 
    width="200" height="150"
    style="border:1px 
    solid #ccc;">
</canvas>

Above snippet This creates a visible canvas area with a border.

Drawing with JavaScript

To draw on the canvas, a 2D drawing context must be obtained using JavaScript. Then methods like fillRect() can be used to draw shapes.

<canvas id="drawBox" 
        width="200" height="150" 
        style="border:1px solid #000;">
</canvas>

<script>
  const canvas = document.getElementById("drawBox");
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "tomato";
  ctx.fillRect(30, 30, 100, 60);
</script>

Common Canvas Methods

Here are some basic drawing methods:

  • fillRect(x, y, width, height) – Draws a filled rectangle.
  • strokeRect(x, y, width, height) – Draws a rectangle outline.
  • clearRect(x, y, width, height) – Clears canvas part.
  • beginPath() – Starts a new drawing path.
  • moveTo(x, y) and lineTo(x, y) – Draw lines.
  • arc(x, y, radius, startAngle, endAngle) – Draw circles or arcs.
<canvas id="myCanvas" 
    width="200" height="200" 
    style="border:1px solid #000;">
</canvas>

<script>
    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");
    ctx.beginPath;
    ctx.arc(100, 100, 50, 0, Math.PI * 2);
    ctx.fillStyle = "skyblue";        
    ctx.fill(); 
    ctx.stroke();
</script>

SVG vs Canvas

SVG is vector-based, meaning graphics are drawn using shapes and paths that scale perfectly without losing quality. SVG elements are part of the DOM, so they can be styled with CSS, accessed with JavaScript, and respond easily to events like clicks or hovers. It’s ideal for static graphics like icons, diagrams, or charts.

Canvas, on the other hand, is pixel-based and provides a blank drawing area that is controlled entirely with JavaScript. It’s great for dynamic graphics like animations, games, or visual effects. Unlike SVG, Canvas content is not part of the DOM, so it’s harder to make interactive unless manually programmed.

The <canvas> element provides a powerful way to draw graphics with JavaScript. It’s ideal for games, animations, charts, and interactive content. While it doesn’t scale like SVG, it offers performance and flexibility for dynamic visuals.

Watch Video on YouTube

HTML Canvas

Scroll to Top