Mastering SVG: From Basics to Advanced Techniques
This comprehensive guide explains what SVG is, how it differs from bitmap images, its XML foundation, basic syntax, viewBox and viewport handling, common shape elements, animation, gradients, usage patterns, comparison with Canvas, optimization tips, fallback strategies, and media‑query integration, all illustrated with code examples and diagrams.
1. What is SVG?
SVG (Scalable Vector Graphics) is an image file format based on XML.
1.1 What is an image file format?
Common image formats include WebP, GIF, PNG, and SVG.
SVG is one of the common image formats.
1.2 What is a vector graphic? What other types of graphics exist?
Vector graphics (also called "vectors") consist of objects such as points and line segments, each with properties like size, direction, color, and position. Vector graphics can be scaled smoothly without loss of quality. The file size depends on complexity, not resolution. Text editing is strong. Compared with bitmap, vectors render faster but lack rich colors.
Bitmap (also called raster graphics) stores pixel arrays with fixed positions and colors.
Each pixel has a specific position and color value.
Colors are expressed in RGB or grayscale.
Vector graphics retain quality when zoomed, unlike bitmaps.
1.3 What is XML markup language?
Extensible Markup Language (XML) is a markup language that allows computers to understand and process structured information.
<message>
<warning>Hello World</warning>
</message>Now we have a basic understanding of SVG.
2. How to use SVG?
2.1 Basic SVG structure
<svg width='440' height='170' xmlns='http://www.w3.org/2000/svg'>
<title>Cat</title>
<desc>Stick Figure of Cat</desc>
<circle cx="100" cy="100" r="50">
<title>我是圆的标题</title>
</circle>
</svg>SVG default size is 300 px × 150 px; the <svg> element defines width and height.
The xmlns attribute defines the SVG namespace.
The <title> element provides a tooltip or title for the image.
Elements allow full description of the image.
HTML tags cannot be used inside SVG content.
2.2 viewBox, viewPort and preserveAspectRatio
To display only a part of an SVG, set the viewBox attribute.
<svg width="100" height="100" viewBox="0 0 100 100">
<circle id="mycircle" cx="50" cy="50" r="50"/>
</svg>Scaling example:
<svg width="100" height="100" viewBox="0 0 50 50">
<circle id="mycircle" cx="50" cy="50" r="50"/>
</svg>From (0,0) the image is enlarged four times.
Viewport vs. viewBox: Viewport is the display area (like a screen). viewBox selects a region and scales it to the viewport. preserveAspectRatio controls alignment and scaling.
Viewport can be set with width="10cm" height="10cm".
<svg width="10cm" height="10cm" style="border:1px solid #666; background-color:pink">
<rect x="50" y="100" width="50" height="50" stroke="#000000" fill="black"/>
<rect x="100" y="100" width="50mm" height="50mm" stroke="#000000" fill="#666"/>
</svg> preserveAspectRatiouses two space‑separated values: the first defines alignment inside the viewport, the second defines how the aspect ratio is preserved.
2.3 Common shapes
<circle>– center ( cx, cy) and radius ( r). Attributes: stroke (outline color), fill (fill color), strokeWidth (outline width).
<circle cx='55' cy='80' r='25' stroke='black' fill='pink' strokeWidth='8'/> <line>– start ( x1, y1) and end ( x2, y2) points; requires stroke to be visible. <path> – uses commands such as M (move), L (line), H (horizontal), V (vertical), C (cubic Bézier), etc.
<svg width="200px" height="200px">
<path d="M10 10"/>
<circle cx="10" cy="10" r="2" fill="red"/>
</svg>The M command moves the pen without drawing; L draws a line. <polygon> – draws a closed shape defined by a list of points.
<polygon fill="transparent" stroke="orange" stroke-width="3" points="0,0 50,0 100,100 0,100 0,0"/> <text>– renders text inside SVG.
<text x="50" y="85" fontSize="35">8</text> <animate>– defines simple animations.
attributeName : name of the animated attribute. from : start value. to : end value. dur : duration. repeatCount : repeat mode.
<rect x="0" y="0" width="100" height="100" fill="#feac5e">
<animate attributeName="x" from="0" to="500" dur="2s" repeatCount="indefinite"/>
</rect> <defs>– defines reusable elements that are not rendered directly.
<svg ...>
<path d="..." fill="url(#paint0_linear)" stroke="url(#paint1_linear)"/>
<defs>
<linearGradient id="paint0_linear" x1="14" y1="-1" x2="14" y2="31" gradientUnits="userSpaceOnUse">
<stop stopColor="#FFF7E8"/>
<stop offset="1" stopColor="#FFA900"/>
</linearGradient>
<linearGradient id="paint1_linear" x1="14" y1="-1" x2="14" y2="31" gradientUnits="userSpaceOnUse">
<stop stopColor="#FFA900"/>
<stop offset="1" stopColor="#FFA900" stopOpacity="0"/>
</linearGradient>
</defs>
</svg>Gradients are defined with linearGradient (linear) or radialGradient (radial). <image> – embeds raster images inside SVG.
<ellipse cx='154' cy='154' rx='150' ry='120' style='fill:#999'/>
<image xlink:href='img.src' x='72' y='92' width='160' height='120'/> <use>– reuses defined symbols.
<svg width="200" height="200" transform="scale(0.4,0.4)">
<defs>
<g id="Port">
<circle style='fill:pink' r="10"/>
</g>
</defs>
<use x="50" y="45" href="#Port"/>
<use x="70" y="89" href="#Port"/>
</svg> <g>– groups elements for shared styling.
<g stroke="black" fill="pink" stroke-width="5">
<circle cx="50" cy="35" r="25"/>
<circle cx="75" cy="35" r="25"/>
<circle cx="150" cy="35" r="25"/>
<circle cx="125" cy="35" r="25"/>
<circle cx="100" cy="35" r="25"/>
</g>2.4 Using SVG files
Insert SVG directly into the DOM and manipulate it with JavaScript and CSS.
<!DOCTYPE html>
<html>
<head></head>
<body>
<svg id="mysvg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600" preserveAspectRatio="xMidYMid meet">
<circle id="mycircle" cx="400" cy="300" r="50"/>
</svg>
</body>
</html>Reference the SVG with an <img> tag. <img src="apple.svg" /> Use it as a CSS background image (avoid base64 encoding to prevent blocking other resources).
background-image: url(bblogo.svg);3. Comparison with Canvas
3.1 Scripted drawing
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75, 50);
ctx.lineTo(100, 75);
ctx.lineTo(100, 25);
ctx.fill();
}Canvas drawing uses pixel‑based rendering and can become blurry when scaled.
3.2 Gradients
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
for (var i = 0; i < 6; i++) {
for (var j = 0; j < 6; j++) {
ctx.strokeStyle = 'rgb(0,' + Math.floor(255-42.5*i) + ',' + Math.floor(255-42.5*j) + ')';
ctx.beginPath();
ctx.arc(12.5 + j*25, 12.5 + i*25, 10, 0, Math.PI*2, true);
ctx.stroke();
}
}
}3.3 Summary
SVG
Canvas
SVG is an XML‑based language for describing 2D graphics. <canvas> is just a drawing surface; drawing requires JavaScript.
Object‑based vector graphics scale without loss.
Canvas renders pixels and loses quality when enlarged.
Each SVG element is a DOM node and can receive events.
Canvas graphics are not separate DOM nodes; they cannot be individually manipulated.
Not suitable for intensive game rendering.
Ideal for image‑heavy games with frequent redraws.
Cannot be saved directly as PNG/JPG; cannot embed raster images.
Can be saved as PNG/JPG and can embed raster images.
4. Development experience
4.1 SVG positioning is convenient
SVG elements can be placed precisely using attributes like alignmentBaseline and textAnchor, avoiding the need to break the document flow.
4.2 Combined rendering approaches
Simple symbols (e.g., fractions, lines) can be rendered with plain HTML when possible.
Complex graphics should stay within SVG to maintain consistent sizing across platforms.
4.3 SVG does not wrap and scales automatically
Because SVG is resolution‑independent, it can adapt to different screen sizes.
4.4 SVG text is selectable and searchable
Unlike PNG or Canvas, text inside SVG remains searchable.
4.5 SVG sprite sheets
Define all icons inside a hidden SVG and reference them with <use>.
Alternatively, use the viewBox attribute to display a specific region, similar to background-position.
4.6 Size optimization
Remove unnecessary attributes; tools such as svgo can automate this.
4.7 Fallback handling
Modern browsers support SVG natively.
For older browsers (e.g., IE8), provide PNG fallbacks.
4.8 SVG with media queries
Media queries inside an embedded SVG can change styles based on device characteristics.
<style type="text/css">
circle {stroke:#000; stroke-width:30; fill:#009688;}
@media (max-width:500px) { circle {fill:#673ab7;} }
@media (min-width:500px) { circle {fill:#ffc107; stroke:pink;} }
</style>5. References
MDN Canvas API, SVG tutorials, gradient guides, optimization articles, and other resources are listed at the end of the original document.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
