Day 59

SVG with JavaScript

11 min
JavaScript 100 Days

SVG (Scalable Vector Graphics) resolution-independent graphics hain — kisi bhi size mein sharp rehte hain. JavaScript se SVG dynamically create aur animate karna charts, icons, aur infographics ke liye useful hai.

SVG with JavaScript

JavaScript se SVG elements create aur modify karo.

svg.js
javascript
const svgNS = "http://www.w3.org/2000/svg";

function createSVG(width, height) {
  const svg = document.createElementNS(svgNS, "svg");
  svg.setAttribute("width", width);
  svg.setAttribute("height", height);
  svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  return svg;
}

function createCircle(cx, cy, r, color) {
  const circle = document.createElementNS(svgNS, "circle");
  circle.setAttribute("cx", cx);
  circle.setAttribute("cy", cy);
  circle.setAttribute("r", r);
  circle.setAttribute("fill", color);
  return circle;
}

const svg = createSVG(400, 300);
document.body.appendChild(svg);

// Animated circles
[50, 150, 250, 350].forEach((x, i) => {
  const circle = createCircle(x, 150, 30 + i * 10, `hsl(${i * 60}, 70%, 60%)`);
  svg.appendChild(circle);
  
  // CSS animation
  circle.style.animation = `pulse ${1 + i * 0.3}s infinite alternate`;
});

🎯 Practice Challenge

SVG bar chart banao — array of data se dynamic bars render karo. Hover par value show karo.