HTML5 Canvas: Drawing with Code

HTML5 Canvas: Drawing with Code in JavaScript: The element is a blank rectangular area on your page.

Concept Explanation

The <canvas> element is a blank rectangular area on your page. But instead of putting HTML tags inside it, you use JavaScript to draw pixels. You can make games, data charts, or complex art.

Think of it like a Robot Artist. You don't say "Draw a circle"; you say "Pick up the red brush, move to (50,50), and draw a line for 360 degrees."


Syntax or Core Structure

Setting up the Context

const canvas = document.querySelector("#my-art");
const ctx = canvas.getContext("2d"); // The "Drawing Tools"

// Draw a Blue Rectangle
ctx.fillStyle = "DodgerBlue";
ctx.fillRect(20, 20, 150, 100); // x, y, width, height

Common Mistakes

  1. Blurry Canvas: Resizing the canvas with CSS (width: 100%) stretches the pixels and makes it look blurry. You MUST set the width and height attributes on the HTML tag itself.
  2. Missing beginPath: If you don't call ctx.beginPath(), JavaScript will think your new drawing is still part of the old one, leading to strange colored lines connecting everything.
  3. Clearing the Frame: If you are making an animation, you must "Wipe" the canvas clean (clearRect) every single frame, or you will leave a "Trail" behind.

Practice Exercises

  1. The Flag Painter: Draw your country's flag (or a simple one like Japan or Italy) using only fillRect.
  2. The Arc Master: Draw a perfectly centered smiley face using the .arc() method.
  3. The Text Writer: Research ctx.strokeText() and write your name in giant hollow letters in the middle of a canvas.