HTML Canvas

Draw graphics with JavaScript.

✍️ 3 exercises + code challenge in this lesson

The <canvas> element is a drawing area. It is empty by default; you draw on it with JavaScript.

  1. Add a canvas with a width and height.
  2. Get its 2D drawing context: canvas.getContext("2d").
  3. Use methods like fillRect(), arc(), fillText() and lineTo().

Canvas is used for charts, games, image editing and animations.

Key Takeaways: HTML Canvas

Mastering HTML Canvas helps you write clean and reliable HTML code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

HTML Canvas Code Example

HTML
<canvas id="c" width="320" height="180" style="border: 1px solid #CBD5E1;"></canvas>
<script>
  const ctx = document.getElementById("c").getContext("2d");

  ctx.fillStyle = "#2563EB";
  ctx.fillRect(20, 20, 100, 60);

  ctx.beginPath();
  ctx.arc(220, 70, 45, 0, Math.PI * 2);
  ctx.fillStyle = "#14B8A6";
  ctx.fill();

  ctx.fillStyle = "#071A2F";
  ctx.font = "bold 20px Arial";
  ctx.fillText("Hello Canvas", 90, 160);
</script>
Free sign-in required · Google login available

HTML Canvas Practice Exercises

Check what you learned in “HTML Canvas”.

/ 3 solved
Fill in the blank

Get the 2D drawing context.

const ctx = canvas.("2d");
✓ Correct! Not quite. Try again.
Multiple choice

Canvas graphics are drawn with…

✓ Correct! Not quite. Try again.
Code challenge

Add a <canvas> element with the id "board", width 300 and height 150.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services