HTML Canvas

The <canvas> element is a blank rectangular bitmap drawing surface on the page. By itself it does nothing — everything you see on a canvas is drawn imperatively using JavaScript. You get a drawing "context" from the canvas element and then call methods on it to paint rectangles, lines, circles, text, and images.

1) Creating a Canvas


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

Always give the canvas fallback content between the tags for browsers/screen readers that don't support it.

2) Getting the 2D Drawing Context


<script>
  // Get a reference to the canvas element
  var canvas = document.getElementById("myCanvas");

  // Ask for a "2d" drawing context — this object has all the drawing methods
  var ctx = canvas.getContext("2d");
</script>

Everything you draw is done through the ctx object, not the <canvas> tag itself.

3) Drawing a Filled Rectangle


ctx.fillStyle = "#3498db";
ctx.fillRect(10, 10, 100, 60); // x, y, width, height

fillRect(x, y, width, height) draws a solid rectangle. Use strokeRect() for an outline only.

4) Drawing a Circle with arc()


ctx.beginPath();
ctx.arc(200, 60, 40, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle
ctx.fillStyle = "#e74c3c";
ctx.fill();

arc() draws circles and arcs. Angles are in radians, so a full circle is 2 * Math.PI.

5) Drawing Text


ctx.font = "16px Arial";
ctx.fillStyle = "#222";
ctx.fillText("Hello Canvas!", 10, 120); // text, x, y

Use fillText() for solid text and strokeText() for outlined text.

6) HTML Size vs CSS Size


<!-- Sets the actual drawing resolution (recommended) -->
<canvas width="300" height="150"></canvas>

<!-- Setting size only with CSS stretches/distorts the drawing -->
<style>
  canvas { width: 600px; height: 300px; } /* avoid unless intentional */
</style>

The width and height attributes set the number of pixels the canvas actually has to draw on. Resizing with CSS instead just stretches that bitmap, making it blurry.

Live Demo

This canvas is drawn live by JavaScript as soon as the page loads: a filled rectangle, a circle, and some text.

Your browser does not support the canvas element.

Best Practices:

  • Set width/height as attributes, not just in CSS, to avoid blurry/stretched drawings.
  • Always check canvas.getContext exists before drawing (older browser support).
  • Wrap related drawing calls with beginPath() to avoid unwanted connected shapes.
  • Canvas content is a flat bitmap — it has no DOM nodes for individual shapes, so it can't be styled with CSS or selected individually.
  • Use Canvas for games, image processing, and pixel-level graphics; use SVG for icons and scalable illustrations.