R
Rishtaara
JavaScript Fundamentals
Lesson 25 of 28Article14 min

Graphics with JavaScript

The <canvas> element is a blank bitmap. JavaScript draws shapes, text, and images with the 2D context API.

Canvas 2D — simple drawing

The <canvas> element is a blank bitmap. JavaScript draws shapes, text, and images with the 2D context API.

Real-life example: Canvas is like a whiteboard. getContext("2d") is your marker — you draw lines, circles, and text pixel by pixel.

Draw on canvas
<canvas id="board" width="300" height="150"></canvas>
Canvas 2D JavaScript
const canvas = document.querySelector("#board");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "#0891b2";
ctx.fillRect(10, 10, 120, 60);

ctx.strokeStyle = "#334155";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(200, 75, 40, 0, Math.PI * 2);
ctx.stroke();

ctx.fillStyle = "#0f172a";
ctx.font = "16px sans-serif";
ctx.fillText("Hello Rishtaara!", 10, 130);

SVG and JavaScript

SVG is vector graphics in HTML — shapes stay sharp when zoomed. JavaScript can change SVG with querySelector, setAttribute, and classList, just like HTML.

Real-life example: Canvas is a painted mural (pixels). SVG is a cut-out paper diagram — you can resize it cleanly and move each piece with JS.

Change SVG with JS
<svg width="100" height="100">
  <circle id="dot" cx="50" cy="50" r="20" fill="orange" />
</svg>
Animate SVG fill
const dot = document.querySelector("#dot");
dot.setAttribute("fill", "#0891b2");
dot.setAttribute("r", "30");