Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

<canvas>

A canvas you draw on from JavaScript: charts, games, effects.

Syntax

<canvas id="board" width="300" height="150"></canvas>

Attributes

ParameterTypeDescription
width, heightnumberThe canvas size in pixels.

Examples

Drawing a rectangle and text:

<canvas id="board" width="240" height="100" style="border: 1px solid #ccc;"></canvas>
 
<script>
  const ctx = document.getElementById("board").getContext("2d");
  ctx.fillStyle = "teal";
  ctx.fillRect(20, 20, 80, 60);
  ctx.fillStyle = "black";
  ctx.font = "20px sans-serif";
  ctx.fillText("Hello", 120, 58);
</script>

Notes

Without JavaScript the canvas is empty. Set its size with the width and height attributes: stretching it only with CSS makes the drawing blurry. What you draw is just pixels that screen readers cannot see, so add a text description.

See also

  • <svg> — Vector graphics right in HTML: shapes, icons, diagrams.
  • <script> — Adds or embeds JavaScript; `<noscript>` shows fallback content when scripts are off.

In the tutorial

  • SVG graphics — SVG vector graphics right in HTML — shapes, viewBox and scaling, strokes and outlines, path, fill and currentColor.

Thanks for reading!

Donate to the site — we work hard for you.