Day 58

Canvas API

14 min
JavaScript 100 Days

Canvas HTML element JavaScript se 2D graphics draw karne deta hai — shapes, images, text, animations. Games, data visualization, image editing — sab Canvas par depend karte hain.

Canvas Basics

Canvas setup karo aur basic shapes draw karo.

canvas.js
javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 600;

// Background
ctx.fillStyle = "#1a1a1a";
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Rectangle
ctx.fillStyle = "#caff46";
ctx.fillRect(50, 50, 200, 100);

// Circle
ctx.beginPath();
ctx.arc(400, 300, 80, 0, Math.PI * 2);
ctx.fillStyle = "rgba(255,100,100,0.8)";
ctx.fill();
ctx.strokeStyle = "#fff";
ctx.lineWidth = 3;
ctx.stroke();

// Text
ctx.fillStyle = "#ffffff";
ctx.font = "bold 32px Arial";
ctx.textAlign = "center";
ctx.fillText("CodingSkillUp!", canvas.width / 2, canvas.height / 2);

// Line
ctx.beginPath();
ctx.moveTo(0, canvas.height);
ctx.lineTo(canvas.width, 0);
ctx.strokeStyle = "#caff46";
ctx.lineWidth = 2;
ctx.stroke();

Animation on Canvas

requestAnimationFrame se canvas animate karo.

canvas-anim.js
javascript
let x = 0, y = 300, dx = 3, dy = 2, radius = 30;

function draw() {
  // Clear
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#1a1a1a";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // Ball
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2);
  ctx.fillStyle = "#caff46";
  ctx.fill();
  
  // Bounce
  x += dx;
  y += dy;
  if (x + radius > canvas.width || x - radius < 0) dx = -dx;
  if (y + radius > canvas.height || y - radius < 0) dy = -dy;
  
  requestAnimationFrame(draw);
}

draw();

🎯 Practice Challenge

Ek mini Paint app banao — mouse drag se draw karo, color picker, brush size, clear button.