- AN in-depth SVG TUTORIAL
- By Flaviocopes.com
- Translation from: The Gold Project
- This article is permalink: github.com/xitu/gold-m…
- Translator: Starrier
- Proofreader: dandyxu, allenlongbaobao
SVG is easy to understand
SVG is an excellent and incredibly powerful image format. This tutorial gives you an overview of SVG by simply explaining everything you need to know.
introduce
Although standardized in the early 2000s, SVG (short for Scalable Vector Graphics) has been a hot topic in recent years.
SVG has been punished for years by poor browser support, especially IE.
I found this to be from a 2011 book: at the time of this writing, SVG embedded directly in HTML worked only in the latest browsers. Seven years later, this is now a thing of the past, and we can safely use SVG images.
Now we can safely use SVG images, unless you have a large number of users with IE8 and later, or with older Android devices. In this case, there is a plan B.
Part of the success of SVG is that we have to support a wide variety of screen resolutions and sizes. SVG solves this problem perfectly.
At the same time, Flash’s rapid decline over the past few years has led to interest in SVG. This is important for a lot of what Flash has done in the past.
SVG is a vector image file format. This makes them very different from other image formats such as PNG, GIF, or JPG, which are raster image file formats.
The advantage of SVG
Since AN SVG image is a vector image, it can be scaled indefinitely and has no problem with image quality degradation. Why is that? Because SVG images are built using XML tags, the browser prints each point and line by drawing them instead of filling some space with predefined pixels. This ensures that SVG images can be adapted to different screen sizes and resolutions, even those not yet invented.
Because they are defined in XML, SVG images are more flexible than JPG or PNG images, and we can interact with them using CSS and JavaScript. SVG image Settings can include CSS and JavaScript.
SVG can render vector-style images that are much smaller than other formats, primarily for logos and illustrations. Another huge use case is ICONS. What was once the icon font field, such as FontAwesome, is now preferred by designers to use SVG images because it is smaller and allows the use of multi-color ICONS.
SVG is simple in terms of animation, which is a very cool topic.
SVG provides several image editing effects, such as masking and clipping, applying filters, and so on.
SVG is just text, so it can be effectively compressed using GZip.
Your first SVG image
SVG images are defined in XML, which means that IF you’re familiar with HTML, SVG will look very familiar. In addition to having tags in SVG for document building (p, article, footer, aside) we also have building blocks for vector graphics: Path, rect, line, etc.
Here is an example of an SVG image:
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" fill="blue" />
</svg>
Copy the code
Notice how easy it is to read and understand what the image looks like: it is a simple blue rectangle of 10 x 10 pixels (the default unit).
For the most part, you don’t have to write SVG code, because you can use tools like Sketch or Figma or any other vector graphics tool to create images and export them as SVG.
The current version of SVG is 1.1, and SVG 2.0 is in development.
Using SVG
Browsers can display SVG images by including them in an IMG tag:
<img src="image.svg" alt="My SVG image" />
Copy the code
Just like any other pixel-based image format:
<img src="image.png" alt="My PNG image" />
<img src="image.jpg" alt="My JPG image" />
<img src="image.gif" alt="My GIF image" />
<img src="image.webp" alt="My WebP image" />
Copy the code
Additionally, SVGS are unique in that they can be included directly in HTML pages:
<! DOCTYPE html> <html> <head> <title>A page</title> </head> <body> <svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" fill="blue" />
</svg>
</body>
</html>
Copy the code
Note that HTML5 and XHTML require different syntax for inline SVG images. Fortunately, XHTML is a thing of the past because it’s too complicated, but if you still need to work with XHTML pages, it’s worth getting to know.
The ability to inline SVG in HTLM makes this format a unicorn in the scene, because other images cannot do this, and a separate request must be opened for each image to get the format.
SVG element
In the example above, you saw the use of the rect element. SVG has many different elements.
The most commonly used is
text
: Creates a text elementcircle
: Creates a circlerect
: Creates a rectangleline
: Creates a linepath
: Creates a path between two pointstextPath
: Creates a path between two points and creates a link text elementpolygon
: Allows you to create polygons of any typeg
: a separate element
The coordinates start at 0,0 in the upper-left corner of the drawing area and represent x from left to right and y from top to bottom.
The image you see reflects the code shown above. Using the browser DevTools, you can check and change them.
text
The text element adds text. You can use the mouse to select text. X and y define the starting point of the text.
<svg>
<text x="5" y="30">A nice rectangle</text>
</svg>
Copy the code
circle
Define circle. Cx and cy are the central coordinates, and r is the radius. Fill is a common property that represents the color of the figure.
<svg>
<circle cx="50" cy="50" r="50" fill="#529fca" />
</svg>
Copy the code
rect
Define a rectangle. X and y are the starting coordinates, and width and height are self-explanatory.
<svg>
<rect x="0" y="0" width="100" height="100" fill="#529fca" />
</svg>
Copy the code
line
X1 and y1 define the starting coordinates. X2 and y2 define the end coordinates. Stroke is a common attribute that represents a line color.
<svg>
<line x1="0" y1="0" x2="100" y2="100" stroke="#529fca" />
</svg>
Copy the code
path
A path is a series of straight lines and curves. It is the most powerful and therefore the most complex of all SVG drawing tools.
D Contains direction commands. These commands start with a command name and a set of coordinates:
M
It takes a set of x and y coordinatesL
That means the line is going to be drawn to it and it takes a set of x’s and y’sH
It’s a horizontal line that only accepts the x-coordinateV
It’s a vertical line, it only accepts the y coordinateZ
Closes the path and puts it back where it startedA
Stands for Arch, which requires a full tutorial of its ownQ
Is a quadratic Bezier curve, again, which requires a full tutorial of its own
<svg height="300" width="300">
<path d="M 100 100 L 200 200 H 10 V 40 H 70"
fill="#59fa81" stroke="#d85b49" stroke-width="3" />
</svg>
Copy the code
textPath
Add text along the shape of the path element.
polygon
Use polygon to draw any polygon. Points represent a set of x, y coordinates and polygons should be linked:
<svg>
<polygon points="9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78," />
</svg>
Copy the code
g
Using the G element, you can group multiple elements:
<svg width="200" height="200">
<rect x="0" y="0" width="100" height="100" fill="#529fca" />
<g id="my-group">
<rect x="0" y="100" width="100" height="100" fill="#59fa81" />
<rect x="100" y="0" width="100" height="100" fill="#59fa81" />
</g>
</svg>
Copy the code
SVG viewport and viewBox
The size of an SVG relative to its container is set by the WIDTH and height attributes of an SVG element. These units default to pixels, but you can use any other common unit, such as % or EM. This is the viewport.
Usually “container” refers to a browser window, but an SVG element can contain other SVG elements, in which case the container is the parent element, SVG.
One important property is the viewBox. It allows you to define a new coordinate system in your SVG canvas.
Suppose you have a simple circle in 200x200px SVG:
<svg width="200" height="200">
<circle cx="100" cy="100" r="100" fill="#529fca" />
</svg>
Copy the code
By specifying the viewBox, you can choose to display only a portion of this SVG. For example, you can start at 0,0 and display only a 100 x 100 px canvas:
<svg width="200" height="200" viewBox="0 0 100 100">
<circle cx="100" cy="100" r="100" fill="#529fca" />
</svg>
Copy the code
Starting at 100,100, you will see another section, the lower right corner of the circle:
<svg width="200" height="200" viewBox="100, 100, 100, 100">
<circle cx="100" cy="100" r="100" fill="#529fca" />
</svg>
Copy the code
A good visualization method is to imagine Google Maps as a giant SVG image, and your browser as a view box the size of the window. As you move, the Viewbox changes its starting point (x,y) coordinates, and as you resize the window, the width and height of the Viewbox change.
Insert SVG into a Web page
There are several ways to add SVG to a Web page.
The most common ones are:
- with
img
The label - With CSS
background-image
attribute - Inline in HTML
- with
object
,iframe
或embed
The label
Check out these examples flavi-svg-loading-ways.glitch.me/at Glitch
withimg
The label
<img src="flag.svg" alt="Flag" />
Copy the code
With CSSbackground-image
attribute
<style>
.svg-background {
background-image: url(flag.svg);
height: 200px;
width: 300px;
}
</style>
<div class="svg-background"></div>
Copy the code
Inline in HTML
<svg width="300" height="200" viewBox="0 0 300 200"
version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Italian Flag</title>
<desc>By Flavio Copes https://flaviocopes.com</desc>
<g id="flag">
<rect fill="green" x="0" y="0" width="100" height="200"></rect>
<rect fill="white" x="100" y="0" width="100" height="200"></rect>
<rect fill="red" x="200" y="0" width="100" height="200"></rect>
</g>
</svg>
Copy the code
withobject
、iframe
或 embed
The label
<object data="flag.svg" type="image/svg+xml"></object>
<iframe src="flag.svg" frameborder="0"></iframe>
<embed src="flag.svg" type="" />
Copy the code
With Embed, you can use the following command to get an SVG document from the parent document
document.getElementById('my-svg-embed').getSVGDocument()
Copy the code
Within SVG, you can refer to a parent document in the following ways:
window.parent.document
Copy the code
Inline SVG using data URLS
You can use any of the above examples to inline SVG into HTML with Data URLs:
<img src="data:image/svg+xml; " alt="Flag" />
<object data="data:image/svg+xml; " type="image/svg+xml"></object>
<iframe data="data:image/svg+xml; " frameborder="0"></iframe>
Copy the code
Also in CSS:
.svg-background {
background-image: url("data:image/svg+xml; ");
}
Copy the code
Simply change < Data > with the appropriate Data URL.
Style element
Any SVG element can accept the style attribute, just like HTML tags. Not all CSS properties will work as you expect. For example, to change the color of a text element, use fill instead of color.
<svg>
<text x="5" y="30" style="fill: green">A nice text</text>
</svg>
<svg>
<text x="5" y="70" style="fill: green; font-family: Courier New">
A nice text
</text>
</svg>
Copy the code
You can also use fill as an element attribute, as you saw earlier:
<svg>
<text x="5" y="70" fill="green">A nice text</text>
</svg>
Copy the code
Other public properties include
fill-opacity
, background color opacitystroke
To define the border colorstroke-width
, set the border width
CSS can target SVG elements just as you target HTML tags:
rect {
fill: red;
}
circle {
fill: blue;
}
Copy the code
Use CSS or JavaSCript to interact with SVG
SVG images can be styled using CSS or scripted using JavaScript, in which case:
- When SVG is inline in HTML
- through
object
、embed
或iframe
Tag when the image is loaded
But (⚠️ depends on the browser implementation) they must be loaded from the same domain (and protocol) due to the same origin policy. The iframe needs to be an explicitly defined size, otherwise the content will be cropped, adjusting both the Object and embed dimensions to fit its content. .
If SVG is loaded with an IMG tag, or if CSS is used as a background, it is source independent:
- CSS and JavaScript cannot interact with it
- JavaScript included in SVG is disabled
- Resources (such as images, stylesheets, scripts, fonts) cannot be loaded externally
details
features | SVG inline | object /embed /iframe |
img |
---|---|---|---|
You can interact with the user | ✅ | ✅ | ✅ |
Support for animation | ✅ | ✅ | ✅ |
You can run JavaScript scripts | ✅ | ✅ | 👎 🏼 |
Scripts can be written externally | ✅ | 👎 🏼 | 👎 🏼 |
Inline SVG images are undoubtedly the most powerful and flexible, and are the only way to perform certain operations with SVG.
If you want SVG to have any interaction with your scripts, it must be loaded inline into HTML.
Loading SVG is especially handy if you don’t need to interact with SVG, just display it on the page, load SVG into IMG, Object, or embed, or if you reuse SVG images in different pages, or if the SIZE of SVG images is quite large.
CSS embedded SVG
Add CSS to CDATA:
<svg> <style> <! [CDATA[#my-rect { fill: blue; }
]]>
</style>
<rect id="my-rect" x="0" y="0" width="10" height="10" />
</svg>
Copy the code
SVG files can also include external style sheets
<? xml version="1.0" standalone="no"? > <? xml-stylesheettype="text/css" href="style.css"? > <svg xmlns="http://www.w3.org/2000/svg" version="1.1"
width=".." height=".." viewBox="..">
<rect id="my-rect" x="0" y="0" width="10" height="10" />
</svg>
Copy the code
JavaScript embed SVG
You can put JavaScript in the first place and wrap it in a Load event to execute it when the page is fully loaded and the SVG is inserted into the DOM:
<svg> <script> <! [CDATA[ window.addEventListener("load", () => {//... },false)
]]>
</script>
<rect x="0" y="0" width="10" height="10" fill="blue" />
</svg>
Copy the code
Or if you place JS at the end of other SVG code, you can avoid adding event listeners and ensure that JavaSCript executes when SVG appears on the page.
<svg>
<rect x="0" y="0" width="10" height="10" fill="blue"/> <script> <! [CDATA[ //... ]]> </script> </svg>Copy the code
Like HTML elements, SVG elements can have ID and class attributes, so we can use the Selectors API to reference them:
<svg>
<rect x="0" y="0" width="10" height="10" fill="blue"
id="my-rect" class="a-rect"/> <script> <! [CDATA[ console.log(document.getElementsByTagName('rect'))
console.log(document.getElementById('my-rect'))
console.log(document.querySelector('.a-rect'))
console.log(document.querySelectorAll('.a-rect'))
]]>
</script>
</svg>
Copy the code
Please see this fault flaviocopes-SVG-script.glitch.me/for functional hints.
JavaScript outside of SVG
If you can interact with SVG (SVG is inline in HTML), you can use JavaScript to change any SVG attribute, such as:
document.getElementById("my-svg-rect").setAttribute("fill"."black")
Copy the code
Or really do whatever DOM manipulation you want.
CSS external to SVG
You can use CSS to change any style of an SVG image.
SVG attributes can be easily overridden in CSS, and they have a lower priority than CSS. They don’t behave like inline CSS, which has a higher priority.
<style>
#my-rect {
fill: red
}
</style>
<svg>
<rect x="0" y="0" width="10" height="10" fill="blue"
id="my-rect" />
</svg>
Copy the code
SVG vs Canvas API
The Canvas API is a great addition to the Web platform with SVG like browser support. The main (and biggest) difference from SVG is that the canvas is not vector-based, but pixel-based, so
- It has the same scaling problems as the pixel-based PNG, JPG, and GIF image formats.
- This makes it impossible to edit canvas images using CSS or JavaScropt, as with SVG.
SVG symbol
Symbol lets you define an SVG image once and reuse it in multiple places. This is a great help if you need to reuse an image, perhaps just by changing some of its properties a little.
You can do this by adding a symbol element and assigning an ID attribute:
<svg class="hidden">
<symbol id="rectangle" viewBox="0 0 20 20">
<rect x="0" y="0" width="300" height="300" fill="RGB (255159, 0)" />
</symbol>
</svg>
Copy the code
<svg>
<use xlink:href="#rectangle" href="#rectangle" />
</svg>
<svg>
<use xlink:href="#rectangle" href="#rectangle" />
</svg>
Copy the code
(Xlink :href is used for Safari support, even though it is a deprecated property)
This allows us to begin to understand the power of SVG.
What if you wanted to use different styles for the two rectangles, for example, a different color for each rectangle? You can use CSS variables.
<svg class="hidden">
<symbol id="rectangle" viewBox="0 0 20 20">
<rect x="0" y="0" width="300" height="300" fill="var(--color)" />
</symbol>
</svg>
Copy the code
<svg class="blue">
<use xlink:href="#rectangle" href="#rectangle" />
</svg>
<svg class="red">
<use xlink:href="#rectangle" href="#rectangle" />
</svg>
<style>
svg.red {
--color: red;
}
svg.blue {
--color: blue;
}
</style>
Copy the code
Check out the SVG symbol — my Glitch playground.
Verify the SVG
SVG files are XML and can be written in invalid formats, and some services or applications may not accept invalid SVG files.
SVG can be validated using the W3C Validator.
I should includexmlns
Attribute?
Sometimes SVG is not defined as
<svg>
...
</svg>
Copy the code
Sometimes defined as
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">... </svg>Copy the code
The second form is XHTML. It can be used with HTML5 (documents with
), but in this case, the first form is simpler.
Should I worry about browser support?
In the 2018 release, the vast majority of users’ browsers support SVG. .
You can still use a library such as Modernizr to check for missing support and provide a backup:
if(! Modernizr.svg) { $(".my-svg").attr("src"."images/logo.png");
}
Copy the code
Diggings translation project is a community for translating quality Internet technical articles from diggings English sharing articles. The content covers the fields of Android, iOS, front end, back end, blockchain, products, design, artificial intelligence and so on. For more high-quality translations, please keep paying attention to The Translation Project, official weibo and zhihu column.