Welcome to the SVG (Scalable Vector Graphics) tutorial! In this lesson, we'll dive deep into the world of SVG, a versatile graphics format that's essential for web developers. By the end of this tutorial, you'll be able to create, modify, and optimize scalable vector graphics for your projects. Let's get started! 📝
SVG stands for Scalable Vector Graphics, an XML-based vector graphics format for two-dimensional graphics with support for interactivity and animation. Unlike raster graphics (like PNG and JPEG), SVG graphics are composed of vectors, which are mathematical representations of graphics primitives such as lines, curves, shapes, and images. This makes SVG images scalable and crisp, regardless of the size or resolution.
An SVG file consists of an XML declaration, an SVG root element, and one or more SVG elements that define the graphics. The root element for an SVG document is <svg>.
<?xml version="1.0" standalone="no"?>
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Your SVG content here -->
</svg>SVG elements have attributes that control various aspects of the graphics, such as dimensions, color, and position. Some common SVG attributes include:
width and height: Define the size of the SVG canvasviewBox: Define the visible part of the SVG and its scaling propertiesfill: Define the filling color or pattern for shapesstroke: Define the outline color and thickness for shapesx and y: Position the element on the canvasLet's create a simple SVG with a square and a circle.
<?xml version="1.0" standalone="no"?>
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<rect x="20" y="20" width="100" height="100" fill="blue"/>
<circle cx="100" cy="100" r="50" fill="red"/>
</svg>In this example, we'll create an animated pie chart using SVG, CSS, and JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
svg {
width: 400px;
height: 400px;
}
path {
fill: #f5f5dc;
}
</style>
</head>
<body>
<svg viewBox="0 0 400 400">
<circle cx="200" cy="200" r="180"/>
<path id="path1" d="M 200,200 m -130,0 a 130,130 0 1 1 0,-260 a 130,130 0 1 1 0,260"/>
<path id="path2" d="M 200,200 m 30,0 a 30,30 0 1 0 0,-60 a 30,30 0 1 0 0,60"/>
</svg>
<script>
const path1 = document.getElementById('path1');
const path2 = document.getElementById('path2');
const duration = 2;
const delay = 0;
const percent = 50;
path1.style.transition = `fill-opacity ${duration}s ease-out ${delay}s`;
path2.style.transition = `fill-opacity ${duration}s ease-out ${delay + 0.5}s`;
path1.style.fillOpacity = 1 - (percent / 100);
path2.style.fillOpacity = percent / 100;
</script>
</body>
</html>What is the root element for an SVG document?
Which SVG attribute defines the visible part of the SVG and its scaling properties?
That's it for this introductory lesson on SVG! In the next lesson, we'll dive deeper into more advanced SVG concepts, including paths, clipping, and transformations. 🚀 Happy coding! 🚀