Scripting SVG: Inline Vector Graphics, createElementNS, Paths and a Data-Driven Pie Chart
Use SVG from JavaScript: SVG as images vs inline markup, viewBox and coordinates, styling SVG with CSS, scripting existing graphics (an animated clock), creating elements with createElementNS, the path d syntax, and building an accessible pie chart from data.
kvi5hnuCode Sprout team member7 min readOn this page
SVG (Scalable Vector Graphics) describes images as shapes, such as circles, lines, paths and text, rather than pixels. It stays sharp at any size, it's usually small, and, when it's written directly inside an HTML page, every shape is a DOM element that CSS can style and JavaScript can script. That makes SVG a natural choice for icons, diagrams, charts and interactive graphics. (The diagrams in this course are SVG files.)
Three ways to put SVG on a page
- As an image:
<img src="logo.svg" alt="...">or a CSSbackground-image. Simple and cacheable, but the SVG is opaque: page scripts and styles can't reach inside it. - Inline: the
<svg>markup written directly in the HTML. Its elements join the DOM, so you can style them with the page's CSS and change them with JavaScript. - Generated by JavaScript: build the elements at run time, for example to chart data loaded from an API.
A small inline example:
<svg id="clock" viewBox="0 0 100 100" width="240" height="240" role="img" aria-label="Clock">
<circle class="face" cx="50" cy="50" r="45" />
<g class="hands">
<line class="hour" x1="50" y1="50" x2="50" y2="28" />
<line class="minute" x1="50" y1="50" x2="50" y2="14" />
</g>
</svg>
viewBox: the drawing's own coordinate system
width and height set how big the graphic is on the page. viewBox="minX minY width height" sets the internal coordinate system the shapes are drawn in. Here, shapes use coordinates from 0 to 100, and the browser scales that square to 240 × 240 CSS pixels. Change the width and the whole drawing scales, with no change to the shapes. As in canvas, the y axis points down.
Styling SVG with CSS
SVG has its own presentation properties, and they can be set with CSS:
#clock .face { fill: #fffbeb; stroke: #1e293b; stroke-width: 3; }
#clock .hands { stroke: #1e293b; stroke-linecap: round; }
#clock .hour { stroke-width: 4; }
#clock .minute { stroke-width: 2; }
.icon:hover path { fill: currentColor; } /* currentColor follows the CSS text color */
fill paints a shape's inside, and stroke its outline. Text inside SVG uses font-family, font-size and font-weight as separate properties. fill: currentColor is the standard trick that lets an inline icon match the color of the text around it.
Scripting an existing SVG
Inline SVG elements can be found with querySelector and changed with setAttribute, just like HTML elements. This makes the clock show the current time by rotating each hand around the center point (50, 50):
function updateClock() {
const now = new Date();
const minutes = now.getMinutes() + now.getSeconds() / 60;
const hours = (now.getHours() % 12) + minutes / 60;
document.querySelector("#clock .minute").setAttribute("transform", `rotate(${minutes * 6} 50 50)`);
document.querySelector("#clock .hour").setAttribute("transform", `rotate(${hours * 30} 50 50)`);
}
updateClock();
setInterval(updateClock, 10_000);
A minute is 6° (360 / 60), and an hour is 30° (360 / 12). The SVG rotate(angle cx cy) transform rotates around a given point.
Attributes are the reliable way to change SVG geometry (cx, r, d, points, transform). Many presentational attributes, such as fill, stroke and opacity, can also be set through CSS, and some geometry properties like r, cx and transform can now be set and animated with CSS in modern browsers.
Creating SVG elements: createElementNS
SVG elements belong to a different XML namespace from HTML. document.createElement("circle") creates an unknown HTML element (an HTMLUnknownElement) that never draws anything. SVG elements must be created with createElementNS, passing the SVG namespace:
const SVG_NS = "http://www.w3.org/2000/svg";
function svgElement(tag, attributes = {}) {
const element = document.createElementNS(SVG_NS, tag);
for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);
return element;
}
const dot = svgElement("circle", { cx: 20, cy: 20, r: 6, fill: "crimson" });
document.querySelector("#clock").append(dot);
Other differences from HTML elements:
- Set SVG attributes with
setAttribute; there are no simple string properties likeimg.src. element.classNameon SVG is anSVGAnimatedStringobject, not a string. UseclassListorsetAttribute("class", ...).- Parsing markup does create real SVG elements:
container.innerHTML = '<svg>...</svg>'uses the HTML parser, which knows about inline SVG. This is convenient for trusted, static markup.
Paths: the universal shape
<path> can draw any shape. Its d attribute is a compact list of commands, each a letter followed by numbers:
| Command | Meaning |
|---|---|
M x y | move to a point without drawing |
L x y | draw a straight line to a point |
H x / V y | horizontal / vertical line |
C x1 y1 x2 y2 x y | cubic Bézier curve with two control points |
Q x1 y1 x y | quadratic Bézier curve with one control point |
A rx ry rotation largeArc sweep x y | elliptical arc to a point |
Z | close the path back to its start |
Uppercase letters use absolute coordinates; lowercase letters (l, c, a) are relative to the current point.
A pie slice is the classic example: move to the center, draw a line to the start of the slice on the circle, draw an arc to its end, and close:

The arc command's two flags choose between the four possible arcs between two points: largeArc is 1 when the slice is more than 180°, and sweep is 1 for clockwise.
Computing slice paths
The math is independent of the DOM, so it runs anywhere. Angles start at the top (12 o'clock) and grow clockwise:
function polar(cx, cy, r, angle) {
const radians = (angle - 90) * Math.PI / 180; // 0° points up, angles grow clockwise
return [cx + r * Math.cos(radians), cy + r * Math.sin(radians)];
}
function slicePaths(data, cx = 100, cy = 100, r = 80) {
const total = Object.values(data).reduce((sum, value) => sum + value, 0);
let start = 0;
return Object.entries(data).map(([label, value]) => {
const sweep = (value / total) * 360;
const end = start + sweep;
const [x1, y1] = polar(cx, cy, r, start);
const [x2, y2] = polar(cx, cy, r, end);
const largeArc = sweep > 180 ? 1 : 0;
const round = (n) => Number(n.toFixed(1));
const d = `M ${cx} ${cy} L ${round(x1)} ${round(y1)} A ${r} ${r} 0 ${largeArc} 1 ${round(x2)} ${round(y2)} Z`;
start = end;
return { label, percent: Math.round((value / total) * 100), d };
});
}
for (const slice of slicePaths({ JavaScript: 62, Python: 45, Java: 33, Go: 13 })) {
console.log(`${slice.label.padEnd(10)} ${String(slice.percent).padStart(3)}% ${slice.d}`);
}
JavaScript 41% M 100 100 L 100 20 A 80 80 0 0 1 144.9 166.2 Z
Python 29% M 100 100 L 144.9 166.2 A 80 80 0 0 1 24 125 Z
Java 22% M 100 100 L 24 125 A 80 80 0 0 1 59.3 31.1 Z
Go 8% M 100 100 L 59.3 31.1 A 80 80 0 0 1 100 20 Z
Each slice ends where the next begins, and the last one ends back at the top, (100, 20).
Turning the paths into a chart
With the paths computed, building the chart is ordinary DOM work, using the svgElement helper from above:
function pieChart(data, colors) {
const svg = svgElement("svg", { viewBox: "0 0 320 200", role: "img", "aria-labelledby": "pie-title" });
const title = svgElement("title", { id: "pie-title" });
title.textContent = "Share of respondents by language";
svg.append(title);
slicePaths(data).forEach((slice, i) => {
const path = svgElement("path", { d: slice.d, fill: colors[i], stroke: "white" });
const tooltip = svgElement("title");
tooltip.textContent = `${slice.label}: ${slice.percent}%`; // shown on hover, read by screen readers
path.append(tooltip);
const swatch = svgElement("rect", { x: 200, y: 30 + i * 28, width: 14, height: 14, fill: colors[i] });
const label = svgElement("text", { x: 222, y: 42 + i * 28, "font-size": 13 });
label.textContent = `${slice.label} ${slice.percent}%`; // textContent: data stays text
svg.append(path, swatch, label);
});
return svg;
}
document.querySelector("#chart").append(
pieChart({ JavaScript: 62, Python: 45, Java: 33, Go: 13 }, ["#2563eb", "#16a34a", "#d97706", "#7c3aed"]),
);
Because each slice is a DOM element, you get interactivity for free: CSS path:hover { opacity: 0.8 }, click handlers with event delegation on the <svg>, and <title> tooltips. role="img" with a <title> gives screen readers a name for the whole chart.
SVG or canvas?
| SVG | Canvas (article 115) | |
|---|---|---|
| Model | retained: shapes are DOM elements | immediate: you paint pixels, nothing is remembered |
| Interactivity | events, CSS and hover on each shape | you do your own hit-testing |
| Scaling | sharp at any size | must be sized for devicePixelRatio |
| Best for | icons, diagrams, charts with up to a few thousand shapes | games, image processing, very many objects, per-frame redraws |
Libraries such as D3 build on SVG's DOM model, while game engines and heavy visualizations use canvas or WebGL.
Common questions
Why doesn't my createElement("circle") show up?
It created an HTML element named circle, which has no meaning in HTML. SVG elements need document.createElementNS("http://www.w3.org/2000/svg", "circle").
How do I make an SVG scale with its container?
Give it a viewBox and set its CSS width (for example, width: 100%), leaving height as auto. The viewBox aspect ratio keeps the proportions.
Can CSS change the color of an SVG used in an img tag?
No. An <img> SVG is an isolated document. Inline the SVG (or use it as a CSS mask-image) to color it with page CSS, typically with fill: currentColor.
Summary
- SVG describes graphics as shapes. Inline SVG elements are part of the DOM, so CSS and JavaScript can work with them.
viewBoxdefines the internal coordinate system;width/heightset the display size.- Style with
fill,strokeand related properties; script geometry withsetAttribute(transform="rotate(a cx cy)",d,cx, ...). - Create SVG elements with
createElementNS("http://www.w3.org/2000/svg", tag), notcreateElement. <path d="...">usesM,L,C,Q,AandZcommands; a pie slice is center, line, arc, close.- Prefer SVG for scalable, interactive graphics with a moderate number of shapes; use canvas for pixel-heavy or very dynamic drawing.
Practice Questions
An SVG has viewBox="0 0 50 50" and width="200". How large is a circle with r="5" on screen?
Answer
The view box is scaled by 200 / 50 = 4, so the radius is 20 CSS pixels and the diameter is 40.
Write the d value for a triangle with corners at (10, 90), (50, 10) and (90, 90).
Answer
M 10 90 L 50 10 L 90 90 Z. Z draws the closing side back to (10, 90).
Which arc flags would a 270° pie slice need, and why?
Answer
largeArc = 1, because the slice covers more than 180°, and sweep = 1, for a clockwise arc like the other slices. With largeArc = 0, the browser would draw the short 90° arc between the same two points.
Why might svgEl.className += " active" misbehave?
Answer
On SVG elements, className is an SVGAnimatedString object, not a string, so string concatenation doesn't do what you expect. Use svgEl.classList.add("active").
Previous: Web Components: Custom Elements, Shadow DOM, Templates and Slots
Next: Drawing with Canvas: Paths, Styles, Text, Images, Transforms, Clipping and Pixels

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.