svg教程_深入的SVG教程

SVG(Scalable Vector Graphics)是一种矢量图像格式,由于其无限缩放和高质量显示特性,近年来备受关注。SVG图像可以通过XML定义,可与CSS和JavaScript交互,适合于多种屏幕尺寸和分辨率。它可以轻松内联在HTML中,提供了丰富的元素和编辑效果,如文字、形状、路径等。此外,SVG还支持动画和各种交互,如CSS和JavaScript的交互。尽管旧版浏览器支持有限,但SVG在现代浏览器中广泛兼容,是网页设计和开发的重要工具。
摘要由CSDN通过智能技术生成

svg教程

介绍 (Introduction)

Despite being standardized in the early 2000s, SVG (a shorthand for Scalable Vector Graphics) is a hot topic these days.

尽管在2000年代初期已经标准化,但是SVG( 可伸缩矢量图形的缩写)是当今的热门话题。

SVG has been penalized for quite a few years by the poor browser support (most notably IE).

SVG已因浏览器支持不佳(最著名的是IE)而受到惩罚。

I found this quote from a 2011 book: “at the time of writing, direct embedding of SVG into HTML works only in the very newest browsers”. 7 years ago, this is now a thing of the past, and we can use SVG images safely.

我从2011年的一本书中发现了这句话:“在撰写本文时,将SVG直接嵌入HTML仅在最新的浏览器中有效”。 7年前,这已经成为过去,我们可以安全地使用SVG图像。

Today we can use SVG images safely, unless you have a lot of users with IE8 and below, or with older Android devices. In this case, fallbacks exist.

今天,我们可以安全地使用SVG图像,除非您有很多使用IE8及以下版本或使用较旧的Android设备的用户。 在这种情况下,存在后备。

SVG Browser support

Some part of the success of SVG is due to the variety of screen displays we must support, at different resolutions and sizes. A perfect task for SVG.

SVG成功的部分原因在于我们必须支持的各种分辨率和尺寸的屏幕显示。 SVG的完美任务。

Also, the rapid decline of Flash in the last few years led to a renewed interest in SVG, which is great for a lot of things that Flash did in the past.

另外,Flash在过去几年中的快速衰落导致人们重新对SVG产生了兴趣,这对Flash过去所做的很多事情都非常有用。

SVG is a vector image file format. This makes them very different than image format such as PNG, GIF or JPG, which are raster image file formats.

SVG是矢量图像文件格式。 这使其与光栅图像文件格式的图像格式(例如PNG,GIF或JPG)大不相同。

SVG的优势 (The advantages of SVG)

SVG images, thanks to being vector images, can infinitely scale and not have any issue in image quality degradation. How so? Because SVG images are built using XML markup, and the browser prints them by plotting each point and line, rather than filling some space with pre-defined pixels. This ensures SVG images can adapt to different screen sizes and resolutions, even ones that have yet to be invented.

SVG图像由于是矢量图像,因此可以无限缩放,并且不会降低图像质量。 为何如此? 由于SVG图像是使用XML标记构建的,因此浏览器通过绘制每个点和线来打印它们,而不是用预定义的像素填充一些空间。 这确保了SVG图像可以适应不同的屏幕尺寸和分辨率,即使尚未发明。

Thanks to being defined in XML, SVG images are much more flexible than JPG or PNG images, and** we can use CSS and JavaScript to interact with them**. SVG images can even contain CSS and JavaScript.

由于使用XML定义,SVG图像比JPG或PNG图像更加灵活 ,并且**我们可以使用CSS和JavaScript与它们进行交互**。 SVG图像甚至可以包含 CSS和JavaScript。

SVG images can render vector-style images a lot smaller than other formats, and are mainly used on logos and illustrations. Another huge use case is icons. Once domain of Icon Fonts like FontAwesome, now designers prefer using SVG images because they are smaller and they allow to have multi-color icons.

SVG图像可以渲染比其他格式小很多的矢量样式图像,并且主要用于徽标和插图。 另一个巨大的用例是图标。 曾经像FontAwesome这样的Icon Font的领域,现在设计人员更喜欢使用SVG图像,因为它们较小并且可以使用多色图标。

SVG is easy to animate, which is a very cool topic.

SVG易于动画制作,这是一个非常酷的话题。

SVG provides some image editing effects, like masking and clipping, applying filters, and more.

SVG提供了一些图像编辑效果,例如蒙版和剪切,应用滤镜等。

SVG are just text, and as such it can be efficiently compressed using GZip.

SVG只是文本,因此可以使用GZip有效压缩。

您的第一个SVG图片 (Your first SVG image)

SVG images are defined using XML. This means that SVG will look very familiar if you are proficient in HTML, except rather than having tags that are suited for document construction (like p, article, footer, aside) in SVG we have the building blocks of vector images: path, rect, line and so on.

SVG图像是使用XML定义的。 这意味着如果您精通HTML,那么SVG会看起来非常熟悉, aside在SVG中拥有适合文档构造的标签(如particlefooteraside ) aside ,我们拥有矢量图像的构建块: pathrectline等。

This is an example SVG image:

这是一个示例SVG图像:

<svg width="10" height="10">
  <rect x="0" y="0" width="10" height="10" fill="blue" />
</svg>

Notice how it’s very easy to read and understand how the image will look like: it’s a simple blue rectangle of 10x10 pixels (the default unit).

请注意,它非常容易阅读和理解图像的外观:它是一个10x10像素的简单蓝色矩形(默认单位)。

Most of the times you won’t have to edit the SVG code, but you will use tools like Sketch or Figma or any other vector graphics tool to create the image, and export it as SVG.

大多数时候,您无需编辑SVG代码,但是您将使用Sketch或Figma之类的工具或任何其他矢量图形工具来创建图像,并将其导出为SVG。

The current version of SVG is 1.1, and SVG 2.0 is under development.

SVG的当前版本是1.1,并且SVG 2.0正在开发中。

使用SVG (Using SVG)

SVG images can be displayed by the browser by including them in a img tag:

通过将SVG图像包含在img标签中,它们可以由浏览器显示:

<img src="image.svg" alt="My SVG image" />

just like you would do for other pixel-based image formats:

就像您要处理其他基于像素的图像格式一样:

<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" />

In addition, pretty uniquely, SVG they can be directly included in the HTML page:

另外,非常独特的是,SVG可以直接包含在HTML页面中:

<!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>

Please note that HTML5 and XHTML require a different syntax for inline SVG images. Luckily XHTML is a thing of the past, as it was more complex than necessary, but it’s worth knowing in case you still need to work on XHTML pages.

请注意,HTML5和XHTML对于嵌入式SVG图像要求使用不同的语法。 幸运的是,XHTML已经成为过去,因为它比必需的更为复杂,但是如果您仍然需要在XHTML页面上工作,则值得一提。

The ability to inline SVG in HTML makes this format a unicorn in the scene, as other images can’t do this, and must be fetched by opening a separate request for each one.

通过HTML内嵌SVG的功能使该格式成为场景中的独角兽 ,因为其他图像无法做到这一点,必须通过为每个图像打开单独的请求来获取该格式。

SVG元素 (SVG Elements)

In the example above you saw the usage of the rect element. SVG has a lot of different elements.

在上面的示例中,您看到了rect元素的用法。 SVG具有许多不同的元素。

The most used ones are

最常用的是

  • text: creates a text element

    text :创建一个文本元素

  • circle: creates a circle

    circle :创建一个圆

  • rect: creates a rectangle

    rect :创建一个矩形

  • line: creates a line

    line :创建一条线

  • path: create a path between two points

    path :在两点之间创建路径

  • textPath: create a path between two points, and a linked text element

    textPath :在两点之间创建一个路径,并创建一个链接的文本元素

  • polygon: allows to create any kind of polygon

    polygon :允许创建任何种类的多边形

  • g: groups separate elements

    g :将单独的元素分组

Coordinates start at 0,0 at the top-left of the drawing area, and extend from left to right for x, from top to bottom for y.

坐标从图形区域左上角的0,0开始, x 左到右延伸, y 上到下延伸。

The images you see reflect the code shown above. Using the Browser DevTools you can inspect and change them.

您看到的图像反映了上面显示的代码。 使用浏览器DevTools可以检查和更改它们。

text (text)

The text element adds text. The text can be selected using the mouse. x and y define the starting point of the text

text元素添加文本。 可以使用鼠标选择文本。 xy定义文本的起点

<svg>
  <text x="5" y="30">A nice rectangle</text>
</svg>

circle (circle)

Define a circle. cx and cy are the center coordinates, and r is the radius. fill is a common attribute and represents the figure color.

定义一个圆。 cxcy是中心坐标, r是半径。 fill是一个常用属性,代表图形颜色。

<svg>
  <circle cx="50" cy="50" r="50" fill="#529fca" />
</svg>

rect (rect)

Defines a rectangle. x, y are the starting coordinates, width and height are self-explanatory.

定义一个矩形。 xy是起始坐标, widthheight不言自明。

<svg>
  <rect x="0" y="0" width="100" height="100" fill="#529fca" />
</svg>

line (line)

x1 and y1 define the starting coordinates. x2 and y2 define the ending coordinates. stroke is a common attribute and represents the line color.

x1y1定义起始坐标。 x2y2定义结束坐标。 stroke是一个常见属性,代表线条颜色。

<svg>
  <line x1="0" y1="0" x2="100" y2="100" stroke="#529fca" />
</svg>

path (path)

A path is a sequence of lines and curves. It’s the most powerful tool to draw using SVG, and as such it’s the most complex.

路径是一系列直线和曲线。 它是使用SVG绘制的最强大的工具,因此也是最复杂的工具。

d contains the directions commands. These commands start with the command name, and a set of coordinates:

d包含Directions命令。 这些命令以命令名称和一组坐标开头:

  • M means Move, it accepts a set of coordinates x, y

    M表示移动,它接受一组坐标x,y

  • L means Line, it accepts a set of coordinates x, y to draw the line to

    L表示线,它接受一组坐标x,y将线绘制到

  • H is an Horizontal Line, it only accept an x coordinate

    H是一条水平线,它仅接受x坐标

  • V is a Vertical Line, it only accept an y coordinate

    V是垂直线,只接受y坐标

  • Z means Close Path, puts a line back to the start

    Z表示“闭合路径”,将行放回起点

  • A means Arch, it needs a whole tutorial on its own

    A指门,它需要本身就是一个完整的教程

  • Q is a quadratic Bezier curve, again it needs a whole tutorial on its own

    Q是二次贝塞尔曲线,同样它需要一个完整的教程

    <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>

textPath (textPath)

Adds a text along the shape of a path element.

沿路径元素的形状添加文本。

<svg
  viewBox="0 0 1000 600"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
>
  <defs>
    <path id="MyPath" d="M 20 40 Q 260 240 400 500" />
  </defs>
  <use xlink:href="#MyPath" fill="none" stroke="#59fa81" />
  <text font-family="Courier New" font-size="42.5">
    <textPath xlink:href="#MyPath">
      Wow such a nice SVG tut
    </textPath>
  </text>
</svg>

polygon (polygon)

Draw any random polygon with polygon. points represents a set of x, y coordinates the polygon should link:

polygon绘制任何随机polygonpoints表示多边形应链接的一组x,y坐标:

<svg>
  <polygon points="9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78" />
</svg>

g (g)

Using the g element you can group multiple elements:

使用g元素可以对多个元素进行分组:

<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="#ad4a3d" />
  </g>
</svg>

SVG视口和viewBox (SVG viewport and viewBox)

The size of an SVG relative to its container is set by the width and height attributes of the svg element. Those units default to pixels, but you can use any other usual unit like % or em. This is the viewport.

SVG相对于其容器的大小由svg元素的widthheight属性设置。 这些单位默认为像素,但是您可以使用任何其他常用单位,例如%em 。 这是视口

Generally “container” means the browser window, but a svg element can contain other svg elements, in that case the container is the parent svg.

通常,“容器”是指浏览器窗口,但是svg元素可以包含其他svg元素,在这种情况下,容器是父svg

An important attribute is viewBox. It lets you define a new coordinates system inside the SVG canvas.

一个重要的属性是viewBox 。 它使您可以在SVG画布内定义新的坐标系。

Say you have a simple circle, in a 200x200px SVG:

假设您在200x200px SVG中有一个简单的圆圈:

<svg width="200" height="200">
  <circle cx="100" cy="100" r="100" fill="#529fca" />
</svg>

By specifying a viewBox you can choose to only show a portion of this SVG. For example you can start at point 0, 0 and only show a 100x100px canvas:

通过指定viewBox,您可以选择仅显示此SVG 的一部分 。 例如,您可以从0、0点开始,仅显示100x100px的画布:

<svg width="200" height="200" viewBox="0 0 100 100">
  <circle cx="100" cy="100" r="100" fill="#529fca" />
</svg>

starting at 100, 100 you will see another portion, the bottom right half of the circle:

从100开始,您将看到另一部分,即圆圈的右下半部分:

<svg width="200" height="200" viewBox="100 100 100 100">
  <circle cx="100" cy="100" r="100" fill="#529fca" />
</svg>

A great way to visualize this is to imagine Google Maps being a gigantic SVG image, and your browser is a viewBox as big as the window size. When you move around, the viewBox changes its starting point (x, y) coordinates, and when you resize the window, you change the width and height of the viewBox.

将此可视化的一种好方法是将Google Maps想象成一个巨大的SVG图像,而您的浏览器是一个与窗口大小一样大的viewBox。 当您四处移动时,viewBox会更改其起点(x,y)坐标,并且在调整窗口大小时,您会更改viewBox的宽度和高度。

在网页中插入SVG (Inserting SVG in Web Pages)

There are various ways to add SVG to a webpage.

有多种方法可以将SVG添加到网页。

The most common ones are:

最常见的是:

  • with an img tag

    带有img标签

  • with the CSS background-image property

    使用CSS background-image属性

  • inline in the HTML

    内联在HTML中
  • with an object, iframe or embed tag

    objectiframeembed标签一起使用

See all these examples live on Glitch: https://glitch.com/edit/#!/flavio-svg-loading-ways

在Glitch上实时查看所有这些示例: https ://glitch.com/edit/#! / flavio-svg-loading-ways

带有img标签 (With an img tag)

<img src="flag.svg" alt="Flag" />

使用CSS background-image属性 (With the CSS background-image property)

<style>
  .svg-background {
    background-image: url(flag.svg);
    height: 200px;
    width: 300px;
  }
</style>
<div class="svg-background"></div>

内联在HTML中 (Inline in the 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>

使用objectiframeembed标签 (With an object, iframe or embed tag)

<object data="flag.svg" type="image/svg+xml"></object>

<iframe src="flag.svg" frameborder="0"></iframe>

<embed src="flag.svg" type="" />

Using embed you have the option to get the SVG document from the parent document using

使用embed您可以选择使用以下命令从父文档中获取SVG文档:

document.getElementById('my-svg-embed').getSVGDocument()

and from inside the SVG you can reference the parent document with:

在SVG内部,您可以通过以下方式引用父文档:

window.parent.document

使用数据URL的嵌入式SVG (Inline SVG using a Data URL)

You can use any of the above examples combined with Data URLs to inline the SVG in the HTML:

您可以将上面的任何示例与数据URL结合使用,以内联HTML中的SVG:

<img src="data:image/svg+xml;<DATA>" alt="Flag" />

<object data="data:image/svg+xml;<DATA>" type="image/svg+xml"></object>

<iframe data="data:image/svg+xml;<DATA>" frameborder="0"></iframe>

and in CSS too:

并且在CSS中:

.svg-background {
  background-image: url('data:image/svg+xml;<DATA>');
}

Just change <DATA> with the appropriate Data URL.

只需使用适当的数据URL更改<DATA>

造型元素 (Styling elements)

Any SVG element can accept a style attribute, just like HTML tags. Not all CSS properties work as you would expect, due to the SVG nature. For example to change the color of a text element, use fill instead of color.

就像HTML标签一样,任何SVG元素都可以接受style属性。 由于SVG的性质,并非所有CSS属性都能按预期工作。 例如,要更改文本元素的颜色,请使用fill而不是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>

You can use fill as an element attribute as well, as you saw before:

您也可以将fill用作元素属性,如前所述:

<svg>
  <text x="5" y="70" fill="green">A nice text</text>
</svg>

Other common properties are

其他常见属性是

  • fill-opacity, background color opacity

    fill-opacity ,背景色不透明度

  • stroke, defines the border color

    stroke ,定义边框颜色

  • stroke-width, sets the width of the border

    stroke-width ,设置边框的宽度

CSS can target SVG elements like you would target HTML tags:

CSS可以定位SVG元素,就像定位HTML标签一样:

rect {
  fill: red;
}
circle {
  fill: blue;
}

通过CSS或JavaScript与SVG交互 (Interacting with a SVG with CSS or JavaScript)

SVG images can be styled using CSS, or scripted with JavaScript, in those cases:

在以下情况下,可以使用CSS设置SVG图像的样式或使用JavaScript编写脚本:

  • when the SVG is inlined in the HTML

    在HTML内联SVG时

  • when the image is loaded through object, embed or iframe tags

    通过objectembediframe标记加载图像时

but (⚠️ depending on the browser implementation) they must be loaded from the same domain (and protocol), due to the same-origin policy.

但是(⚠️取决于浏览器的实现),由于同源策略,它们必须从相同的域(和协议)加载。

iframe needs to be explicitly sized, otherwise the content is cropped, while object and embed resize to fit their content.

需要明确调整iframe大小,否则裁剪内容,同时调整objectembed大小以适合其内容。

If the SVG is loaded using a img tag, or through CSS as a background, independently of the origin:

如果使用img标签或通过CSS作为背景加载SVG,而与来源无关:

  • CSS and JavaScript cannot interact with it

    CSS和JavaScript无法与其交互
  • JavaScript contained in the SVG is disabled

    SVG中包含JavaScript被禁用
  • External resources like images, stylesheets, scripts, fonts cannot be loaded

    无法加载外部资源,例如图像,样式表,脚本,字体

in detail

详细地



FeatureInline SVGobject/embed/iframeimg
Can interact with the user
Supports animations
Can run its own JavaScript👎🏼
Can be scripted from outside👎🏼👎🏼
特征 内联SVG object / embed / iframe img
可以与用户互动
支持动画
可以运行自己JavaScript 👎🏼
可以从外部编写脚本 👎🏼 👎🏼

Inline SVG images are definitely the most powerful and flexible, and it’s the only way to perform certain operations with SVG.

内联SVG映像绝对是最强大和灵活的,并且是使用SVG执行某些操作的唯一方法。

If you want to do any interaction with the SVG with your scripts, it must be loaded inline in the HTML.

如果要使用脚本与SVG进行任何交互,则必须将其内联加载到HTML中

Loading an SVG in an img, object or embed works if you don’t need to interact with it, just show it in the page, and it’s especially convenient if you reuse SVG images in different pages, or the SVG size is quite big.

如果您不需要与SVG交互,只需将其加载到imgobjectembed即可,只需在页面中显示即可,如果在不同页面中重复使用SVG图像,或者SVG尺寸很大,则特别方便。

SVG中CSS (CSS inside SVG)

Add the CSS in a CDATA:

在CDATA中添加CSS:

<svg>
  <style>
    <![CDATA[
      #my-rect { fill: blue; }
    ]]>
  </style>
  <rect id="my-rect" x="0" y="0" width="10" height="10" />
</svg>

An SVG file can also include an external style sheet:

SVG文件还可以包含外部样式表:

<?xml version="1.0" standalone="no"?>
<?xml-stylesheet type="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>

SVG中JavaScript (JavaScript inside SVG)

You can put the JavaScript first, and wrap in in a load event to execute it when the page is fully loaded and the SVG is inserted in the DOM:

您可以将JavaScript放在第一位,并包装在load事件中以在页面完全加载并且SVG插入DOM时执行它:

<svg>
  <script>
    <![CDATA[ window.addEventListener("load", () => { //... }, false) ]]>
  </script>
  <rect x="0" y="0" width="10" height="10" fill="blue" />
</svg>

or you can avoid adding an event listener if you put the JS at the end of the other SVG code, to make sure the JavaScript runs when the SVG is present in the page:

或者,如果您将JS放在其他SVG代码的末尾,则可以避免添加事件侦听器,以确保当页面中出现SVG时JavaScript可以运行:

<svg>
  <rect x="0" y="0" width="10" height="10" fill="blue" />
  <script>
    <![CDATA[ //... ]]>
  </script>
</svg>

SVG elements, just like html tags, can have id and class attributes, so we can use the Selectors API to reference them:

SVG元素就像html标签一样,可以具有idclass属性,因此我们可以使用Selectors API来引用它们:

<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>

Check out this Glitch https://glitch.com/edit/#!/flaviocopes-svg-script for an example of this functionality.

查看此Glitch https://glitch.com/edit/#!/flaviocopes-svg-script以获取此功能的示例。

SVG之外JavaScript (JavaScript outside the SVG)

If you can interact with the SVG (the SVG is inline in the HTML), you can change any SVG attribute using JavaScript, for example:

如果可以与SVG交互(SVG在HTML中是内联的),则可以使用JavaScript更改任何SVG属性,例如:

document.getElementById('my-svg-rect').setAttribute('fill', 'black')

or really do any other DOM manipulation you want.

或确实执行您想要的任何其他DOM操作。

SVG之外CSS (CSS outside the SVG)

You can change any styling of the SVG image using CSS.

您可以使用CSS更改SVG图像的任何样式。

SVG attributes can be easily overwritten in CSS, and they have a lower priority over CSS. They do not behave like inline CSS, which has higher priority.

SVG属性很容易在CSS中覆盖,并且它们的优先级比CSS低。 它们的行为不像内联CSS,后者具有更高的优先级。

<style>
  #my-rect {
    fill: red;
  }
</style>
<svg>
  <rect x="0" y="0" width="10" height="10" fill="blue" id="my-rect" />
</svg>

SVG与Canvas API (SVG vs Canvas API)

The Canvas API is a great addition to the Web Platform, and it has similar browser support as SVG. The main (and big) difference with SVG is that Canvas is not vector based, but rather pixel based, so

Canvas API是Web平台的一个重要补充,它具有与SVG相似的浏览器支持。 SVG的主要(也是最大的)区别是Canvas不是基于矢量的,而是基于像素的,因此

  • it has the same scaling issues as pixel-based PNG, JPG and GIF image formats

    它具有与基于像素的PNG,JPG和GIF图像格式相同的缩放问题
  • it makes it impossible to edit a Canvas image using CSS or JavaScript like you can do with SVG

    这样就无法像使用SVG一样使用CSS或JavaScript编辑Canvas图像

SVG符号 (SVG Symbols)

Symbols let you define an SVG image once, and reuse it in multiple places. This is a great help if you need to reuse an image, and maybe just change a bit some of its properties.

使用符号可以一次定义SVG图像,然后在多个位置重复使用。 如果您需要重用图像,也许只是稍微更改其某些属性,则这是一个很大的帮助。

You do so by adding a symbol element and assigning an id attribute:

为此,您可以添加一个symbol元素并分配一个id属性:

<svg class="hidden">
  <symbol id="rectangle" viewBox="0 0 20 20">
    <rect x="0" y="0" width="300" height="300" fill="rgb(255,159,0)" />
  </symbol>
</svg>
<svg>
  <use xlink:href="#rectangle" href="#rectangle" />
</svg>

<svg>
  <use xlink:href="#rectangle" href="#rectangle" />
</svg>

(xlink:href is for Safari support, even if it’s a deprecated attribute)

( xlink:href用于Safari支持,即使它是已弃用的属性也是如此)

This starts to give an idea of the power of SVG.

这开始使人对SVG的功能有了一个了解。

If you want to style those 2 rectangles differently, for example using a different color for each? You can use CSS Variables.

如果要为这两个矩形设置不同的样式,例如为每个矩形使用不同的颜色? 您可以使用CSS变量

<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>
<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>

See my Glitch playground on SVG symbols.

在SVG符号上查看我的Glitch游乐场

验证SVG (Validate an SVG)

An SVG file, being XML, can be written in an invalid format, and some services or apps might not accept an invalid SVG file.

可以将XML格式的SVG文件写入无效格式,并且某些服务或应用程序可能不接受无效的SVG文件。

SVG can be validated using the W3C Validator.

可以使用W3C验证程序来验证SVG。

我应该包括xmlns属性吗? (Should I include the xmlns attribute?)

Sometimes an svg is defined as

有时svg被定义为

<svg>
  ...
</svg>

sometimes as

有时

<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
  ...
</svg>

This second form is XHTML. It can also be used with HTML5 (documents with <!DOCTYPE html>) but in this case the first form is simpler.

第二种形式是XHTML。 它也可以与HTML5(带有<!DOCTYPE html>文档)一起使用,但是在这种情况下,第一种形式更简单。

我应该担心浏览器支持吗? (Should I worry about browser support?)

Today SVG is supported by the vast majority of user’s browsers.

如今,绝大多数用户的浏览器都支持SVG。

You can still check for missing support using libraries like Modernizr, and provide a fallback:

您仍然可以使用Modernizr之类的库来检查缺少的支持,并提供一个后备:

if (!Modernizr.svg) {
  document.querySelector('.my-svg').setAttribute('src', 'images/logo.png')
}

翻译自: https://flaviocopes.com/svg/

svg教程

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值