Learn web development

在网页中添加矢量图形

矢量图形在很多情况下非常有用 — 它们拥有较小的文件尺寸,却高度可缩放,所以它们不会在镜头拉近或者放大图像时变成马赛克风格。在这篇文章中,我们将为您呈现如何在网页中添加矢量图形。

前提: 你需要了解 HTML的基本知识 并且知道如何 在你的文档中插入图片.
目标: 了解如何嵌入 SVG (矢量) 图形到网页中。

提示: 本文的目的并不是教你 SVG; 仅仅是告诉你它是什么,以及如何在网页中添加它。

什么是矢量图形?

在网上,你会和两种类型的图片打交道 — 位图和矢量图:

  • 位图使用像素网格来定义 — 一个位图文件精确得包含了每个像素的位置和它的色彩信息。流行的位图格式包括 Bitmap (.bmp), PNG (.png), JPEG (.jpg), and GIF (.gif.)
  • 矢量图使用算法来定义 — 一个矢量图文件包含了图形和路径的定义,电脑可以根据这些定义计算出当它们在屏幕上渲染时应该呈现的样子。 SVG 格式可以让我们创造用于 Web 的精彩的矢量图形。

为了让你清楚的认识到两者的区别,我们来一个例子。你可以在我们的 Github 仓库中在线查看这个例子:vector-versus-raster.html — 它并排展示了两个看起来一致的图像,一个红色的五角星以及黑色的阴影。不同的是,左边的是 PNG,而右边的是 SVG 图像。

Two star images, one raster and one vector. At their default size they look identical

当你放大网页的时候,区别就会变得明显起来 — 随着你的放大,PNG 图片变得像素化了,因为它存储是每个像素的颜色和位置信息 — 当它被放大时,每个像素就被放大以填满屏幕上更多的像素,所以图像就会开始变得马赛克感觉。矢量图像看起来仍然效果很好且清晰,因为无论它的尺寸如何,都使用算法来计算出图像的形状,仅仅是根据放大的倍数来调整算法中的值。

Two star images zoomed in. The raster one on the left starts to look pixellated, whereas the vector one still looks crisp.

此外,矢量图形相较于同样的位图,通常拥有更小的体积,因为它们仅需储存少量的算法,而不是逐个储存每个像素的信息。

SVG是什么?

SVG is an XML-based language for describing vector images. It's basically markup, like HTML, except that you've got many different elements for defining the shapes you want to appear in your image, and the effects you want to apply to those shapes. SVG is for marking up graphics, not content. At the simplest end of the spectrum, you've got elements for creating simple shapes, like <circle> and <rect>. More advanced SVG features include <feColorMatrix> (transform colors using a transformation matrix,) <animate> (animate parts of your vector graphic,) and <mask> (apply a mask over the top of your image.)

As a simple example, the following code creates a circle and a rectangle:

<svg version="1.1"
     baseProfile="full"
     width="300" height="200"
     xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%" fill="black" />
  <circle cx="150" cy="100" r="90" fill="blue" />
</svg>

This creates the following output:

From the example above, you may get the impression that SVG is easy to handcode. Yes, you can handcode simple SVG in a text editor, but for a complex image this quickly starts to get very difficult. For creating SVG images, most people use a vector graphics editor like Inkscape or Illustrator. These packages allow you to create a variety of illustrations using various graphics tools, and create approximations of photos (for example Inkscape's Trace Bitmap feature.)

SVG has some additional advantages besides those described so far:

  • Text in vector images remains accessible (which also benefits your SEO).
  • SVGs lend themselves well to styling/scripting, because each component of the image is an element that can be styled via CSS or scripted via JavaScript.

So why would anyone want to use raster graphics over SVG? Well, SVG does have some disadvantages:

  • SVG can get complicated very quickly, meaning that file sizes can grow; complex SVGs can also take significant processing time in the browser.
  • SVG can be harder to create than raster images, depending on what kind of image you are trying to create.
  • SVG is not supported in older browsers, so may not be suitable if you need to support older versions of Internet Explorer with your web site (SVG started being supported as of IE9.)

Raster graphics are arguably better for complex precision images such as photos, for the reasons described above.

Note: In Inkscape, save your files as Plain SVG to save space. Also, please refer to this article describing how to prepare SVGs for the Web.

Adding SVG to your pages

In this section we'll go through the different ways in which you can add SVG vector graphics to your web pages.

The quick way: <img>

To embed an SVG via an <img> element, you just need to reference it in the src attribute as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please read Images in HTML.

<img
    src="equilateral.svg"
    alt="triangle with all three sides equal"
    height="87px"
    width="100px" />

Pros

  • Quick, familiar image syntax with built-in text equivalent available in the alt attribute.
  • You can make the image into a hyperlink easily by nesting the <img> inside an <a> element.

Cons

  • You cannot manipulate the image with JavaScript.
  • If you want to control the SVG content with CSS, you must include inline CSS styles in your SVG code. (External stylesheets invoked from the SVG file take no effect.)
  • You cannot restyle the image with CSS pseudoclasses (like :focus).

Troubleshooting and cross-browser support

To support SVG browsers that don't support SVG (IE 8 and below, Android 2.3 and below), you could reference a PNG or JPG from your src attribute and use a srcset attribute (which only recent browsers recognize) to reference the SVG. This being the case, only supporting browsers will load the SVG — older browsers will load the PNG instead:

<img src="equilateral.png" alt="triangle with equal sides" srcset="equilateral.svg">

You can also use SVGs as CSS background images, as shown below. In the below code, older browsers will stick with the PNG that they understand, while newer browsers will load the SVG:

background: url("fallback.png") no-repeat center;
background-image: url("image.svg");
background-size: contain;

Like the <img> method described above, inserting SVGs using CSS background images means that the SVG can't be manipulated with JavaScript, and is also subject to the same CSS limitations.

If your SVGs aren't showing up at all, it might be because your server isn't set up properly. If that's the problem, this article will point you in the right direction.

How to include SVG code inside your HTML

You can also open up the SVG file in a text editor, copy the SVG code, and paste it into your HTML document — this is sometimes called putting your SVG inline, or inlining SVG. Make sure your SVG code snippet begins and ends with the <svg></svg> tags (don't include anything outside those.) Here's a very simple example of what you might paste into your document:

<svg width="300" height="200">
    <rect width="100%" height="100%" fill="green" />
</svg>

Pros

  • Putting your SVG inline saves an HTTP request, and therefore can reduce your loading time.
  • You can assign classes and ids to SVG elements and style them with CSS, either within the SVG or wherever you put the CSS style rules for your HTML document. In fact, you can use any SVG presentation attribute as a CSS property.
  • Inlining SVG is the only approach that lets you use CSS interactions (like :focus) and CSS animations on your SVG image (even in your regular stylesheet.)
  • You can make SVG markup into a hyperlink by wrapping it in an <a> element.

Cons

  • This method is only suitable if you're using the SVG in only one place. Duplication makes for resource-intensive maintenance.
  • Extra SVG code increases the size of your HTML file.
  • The browser cannot cache inline SVG as it would cache regular image assets.
  • You may include fallback in a <foreignObject> element, but browsers that support SVG still download any fallback images. You need to weigh whether the extra overhead is really worthwhile, just to support obsolescent browsers.

How to embed an SVG with an <iframe>

You can open SVG images in your browser just like webpages. So embedding an SVG document with an <iframe> is done just like we studied in From <object> to <iframe> — other embedding technologies.

Here's a quick review:

<iframe src="triangle.svg" width="500" height="500" sandbox>
    <img src="triangle.png" alt="Triangle with three unequal sides" />
</iframe>

This is definitely not the best method to choose:

Cons

  • iframes do have a fallback mechanism, as you can see, but browsers only display the fallback if they lack support for iframes altogether.
  • Moreover, unless the SVG and your current webpage have the same origin, you cannot use JavaScript on your main webpage to manipulate the SVG.

Active Learning: Playing with SVG

In this active learning section we'd like you to simply have a go at playing with some SVG for fun. In the Input section below you'll see that we've already provided you with some samples to get you started. You can also go to the SVG Element Reference, find out more details about other toys you can use in SVG, and try those out too. This section is all about practising your research skills, and having some fun.

If you get stuck and can't get your code working, you can always reset it using the Reset button.

Summary

This article has provided you with a quick tour of what vector graphics and SVG are, why they are useful to know about, and how to include SVG inside your webpages. It was never intended to be a full guide to learning SVG, just a pointer so you know what SVG is if you meet it in your travels around the Web. So don't worry if you don't feel like you are an SVG expert yet. We've included some links below that might help you if you wish to go and find out more about how it works.

In the last article of this module we will explore responsive images in detail, looking at the tools HTML has to allow you to make your images work better across different devices.

See also

文档标签和贡献者