preface

This article documents the basics of SVG. Paper come zhongjue shallow, to know this must practice. Come on, please read it with me.

What is SVG?

SVG stands for Scalable Vector Graphics. It is a graphical format in which shapes are specified in XML. The XML is then rendered by the SVG viewer.

Classification of graphics in computers

Generally can be divided into two categories: bitmap, vector map. A bitmap, also known as a bitmap or raster image, is made up of individual points called pixels (picture elements). An ordinary photograph is a bitmap, which is made up of pixels that become blurred when enlarged. Vector images are more like point-to-point position filling, with no concept of resolution, and the image can be enlarged or shrunk at will without distortion.

Advantages of SVG

[1] Unlimited expansion, printing display without distortion

[2] SVG can be controlled in the same way as everyday coding, with almost no cost to use

[3] Occupies very little space (relative to bitmaps) and can be further compressed by gzip compression

[4] SVG is rendered by XML, and dom is its essence

SVG compatibility

SVG graphic

[1] Basic reference method of SVG

Displaying SVG in a Web browser (such as Chrome, Firefox, and Internet Explorer) allows the browser to point to the URL of an SVG file, embed SVG in an HTML page, use an iframe element, There are four main ways to implement reference 1 using methods such as the IMG element: use the iframe element

<iframe :src="require('@/assets/data-show/banner/bt-image-09.png')" >
Copy the code

2: Use the IMG element

<img class="s-left" :src="require('@/assets/data-show/banner/bt-image-09.png')" />
Copy the code

3: use embed

<embed :src="require('@/assets/data-show/banner/bt-image-09.png')" pluginspage="http://www.adobe.com/svg/viewer/install/" />
Copy the code

4: Embed HTML directly

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> </head> <body> < SVG width="500" height="500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg> </body> </html>Copy the code

A variety of reference methods to choose which completely depends on their own needs to define, each has its own strengths.

features SVG inline object/embed/iframe img
Can interact with the user
Support for animation
You can run JS scripts
Scripts can be written externally

[2] SVG line attributes

attribute describe
fill Sets the fill color of the shape
fill-opacity Sets the fill opacity of the shape
stroke Sets the color of the stroke (line) used to draw the outline of this shape
stroke-width Sets the width of stroke (line) used to draw the outline of this shape
stroke-dasharray Sets the stroke (dashed line) used to draw the outline of this shape
stroke-opacity Sets the opacity of the stroke (line) used to draw the outline of this shape

[3] Introduction to basic graphic elements of SVG

SVG

<rect x="10" y="10" height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
Copy the code

SVG

<circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>
Copy the code

Ellipse: SVG

<ellipse cx="40" cy="40" rx="30" ry="15" style="stroke:#006600; fill:#00cc00"/>
Copy the code

SVG

<line x1="0" y1="10" x2="0" y2="100" style="stroke:#006600;"></line>
Copy the code

Polyline: SVG

<polyline fill="none" stroke="black"  points="20,100 40,60 70,80 100,20"/>
Copy the code

Poly: SVG

<polygon points="10, 0, 0, 35, 50 60." " style="stroke:#660000; fill:#cc3333;"/>
Copy the code

[4] Create SVG coordinate system and build complete pattern

We create a two-dimensional coordinate system with x representing the horizontal axis and y representing the vertical axis in pixels (px) by default. X goes up to the right, y goes up to the down. This is the opposite of what we think of as cartesian coordinates.

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content="ie=edge"> <title>SVG</title> <style type="text/ CSS "> html, body { height: 100%; width: 100%; background: #e9e9e9; } body { margin: 0; text-align: center; } .grid { width: 500px; height: 500px; margin: 0 auto; padding-top: 100px; padding-left: 100px; background-image: url('grid.png'); position: relative; } .grid::before { content: ""; border-left: 1px solid #7c7cea; position: absolute; top: 0; left: 100px; width: 50px; height: 600px; } .grid::after { content: ""; border-top: 1px solid #7c7cea; position: absolute; top: 100px; left: 0; width: 600px; height: 500px; } .st0{fill-rule:evenodd; clip-rule:evenodd; fill:#FFFFFF; } </style> </head> <body> <div class="grid"> < SVG version="1.1" width="500" height="500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <polyline class="right-ear" style="stroke:#583504; stroke-width: 3; Fill :#fddb55" points="120, 80250, 180120, 180120,80"/> <polyline class="left-ear" style="stroke:#583504; stroke-width: 3; Fill :#fddb55" points=" 360 "/> <circle Cx ="250" cy="250" r="150" style="stroke:#583504; stroke-width: 3; fill:#fddb55"/> <circle cx="183" cy="178" r="16" style="fill:#FFFFFF"/> <circle cx="273" cy="180" r="18" style="fill:#FFFFFF"/> <g class="right-eye"> <ellipse cx="170" cy="215" rx="45" ry="20" style="stroke:#583504; stroke-width: 3; fill:#FFFFFF"/> <circle cx="185" cy="215" r="18" style="stroke:#583504; stroke-width: 1; fill:#583504"/> </g> <g class="left-eye"> <ellipse cx="300" cy="215" rx="45" ry="20" style="stroke:#583504; stroke-width: 3; fill:#FFFFFF"/> <circle cx="315" cy="215" r="18" style="stroke:#583504; stroke-width: 1; Fill :#583504"/> </g> <g class="nose"> <path ID =" path "transform='translate(117 235) scale(1.6)' class="st0" D = "M39.9 c2.5 12.9-7.5, 9.3, 11.6, 20.4 12.3 S80.1, 3,86.4, 10 c6, 7-5.6, 15.7, 8.7, 26.9 9.4 s20.5, 2.5, 28,9.4 ,53.1 c13.3, 14.8, 13.3, 32.5, 0-16.7 c, 22.1-38.5, 33.1-65.3, 33 c - 15.7-0.4-31.9-6.7-48.6-19.1 C9.4, 63.9, 0.3, 49.6, 0.2, 34.4 C0.3-9.8, 4.6-17 S30.5, 13-21.5, 8.3, 39.9, 12.9 z "/ > < the ellipse cx =" 225 "cy =" 285 "rx =" 30 "ry =" 18 "style =" stroke: # 583504; stroke-width: 3; fill:#583504"/> <line x1="225" y1="295" x2="225" y2="325" style="stroke:#583504; stroke-width: 5;" ></line> <line x1="190" y1="325" x2="275" y2="325" style="stroke:#583504; stroke-width: 5;" ></line> </g> </svg> </div> </body> </html>Copy the code

The above code results

SVG code reuse problem

We know that SVG’s blocks of code are extremely large and complex, but in order to save as much code as possible, SVG has also developed a solution for code reuse (that is, a componentlike approach to combining complex patterns from base components).

【 1 】<g>The element

The

element treats all child elements as a combination. Often the combination also has a unique ID as a name. The style specified by the element also applies to all child elements unless it is set separately.

 <svg version="1.1"
         width="500" height="500"
         xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink"> <! -- g#house nested g#man and g#woman --><g id="house" style="fill:none; stroke:black;" width="240px" height="240px">
            <title>house</title>
            <desc>House width door</desc>
            <rect x="6" y="50" width="60" height="60"></rect>
            <polyline points="Six 50 4 9,66"></polyline>
            <polyline points="35 110,36 80,50 80,50 110" />
        </g>
        <g id="man" style="fill:none; stroke:black;">
            <title>man</title>
            <desc>Male human</desc>
            <circle cx="85" cy="56" r="10" />
            <line x1="85" y1="66" x2="85" y2="80" />
            <polyline points="76 104 80 hanjie xuebao/transactions of 30 104" />
            <polyline points="76 70 76 hanjie xuebao/transactions of 30 70" />
        </g>
        <g id="woman" style="fill:none; stroke:black;">
            <title>woman</title>
            <desc>Female human</desc>
            <circle cx="110" cy="56" r="10" />
            <polyline points="110 66,110 80,100 90,120 90,110 80" />
            <line x1="104" y1="104" x2="108" y2="90" />
            <line x1="112" y1="90" x2="116" y2="104" />
            <polyline points="101, 70110, 76119, 80" />
        </g>
    </svg>
Copy the code

【 2 】<use>The element

Repeating elements are common in complex graphics, and SVG uses

elements to provide complex pasting capabilities for combinations defined within

elements or for arbitrary independent graphic elements; Once you have defined a set of

graphic objects, display them again using the

tag. To specify the combination you want to reuse, give the URI to the xlink:href attribute, along with the x and y positions to indicate where the combination should be moved.



<use xlink:href="#house" x="70" y="100"></use> /< / house module use xlink: href = "# man" x = "and 55" y = "100" > < / use> / / man module
<use xlink:href="#woman" x="To 50" y="100"></use> / / woman module
Copy the code

[3]<defs>The element

The

element can be used as a container to hold all reusable elements and not display them, just use them as templates

<svg version="1.1"
         width="500" height="500"
         xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink">
        <defs>
	        <g id="house" style="fill:none; stroke:red;" width="240px" height="240px">
	            <title>house</title>
	            <desc>House width door</desc>
	            <rect x="6" y="50" width="60" height="60"></rect>
	            <polyline points="Six 50 4 9,66"></polyline>
	            <polyline points="35 110,36 80,50 80,50 110" />
	        </g>
	        <g id="man" style="fill:none; stroke:black;">
	            <title>man</title>
	            <desc>Male human</desc>
	            <circle cx="85" cy="56" r="10" />
	            <line x1="85" y1="66" x2="85" y2="80" />
	            <polyline points="76 104 80 hanjie xuebao/transactions of 30 104" />
	            <polyline points="76 70 76 hanjie xuebao/transactions of 30 70" />
	        </g>
	        <g id="woman" style="fill:none; stroke:black;">
	            <title>woman</title>
	            <desc>Female human</desc>
	            <circle cx="110" cy="56" r="10" />
	            <polyline points="110 66,110 80,100 90,120 90,110 80" />
	            <line x1="104" y1="104" x2="108" y2="90" />
	            <line x1="112" y1="90" x2="116" y2="104" />
	            <polyline points="101, 70110, 76119, 80" />
	        </g>
        </defs>
        <use xlink:href="#house" x="70" y="100"></use>
        <use xlink:href="#man" x="And 55" y="100"></use>
        <use xlink:href="#woman" x="To 50" y="100"></use>
    </svg>
Copy the code

[4]<symbol>The element

<symbol>Elements are essentially containers that can be put together to create complex patterns. In addition<symbol>Elements and<g>Elements differ in that they can be specifiedviewBoxandpreserveAspectRatioProperty, by giving<use>The element adds width and height attributes to make the symbol fit the viewport size. Here is a brief introductionviewPort,viewBoxwithpreserveAspectRatio.

viewPort: Simply put, the size of the area to display is the screen size. If the specific size is set, the set size prevails (mixed units are supported but not recommended).

ViewBox: A viewBox has four arguments (min-x, min-y, width, height). Min-x: abscissa of the upper left corner, min-y: ordinate of the upper left corner, width: width, height: height By default, the origin is in the upper left corner, X-axis horizontally to the right, Y-axis vertically down

So essentially the viewBox is changing coordinates and units, changing the region image to user coordinates and user units so how do you get that? Here’s an example

<svg width="500" height="200" viewBox="0 0 50 20" >
    <rect x="20" y="10" width="10" height="5"
          style="stroke: #000000; fill:none;"/>
</svg>
Copy the code

This example creates < SVG > an element with a width of 500 pixels and a height of 200. The viewBox property < SVG > contains four coordinates. These coordinates define the ViewBox for the < SVG > element. The coordinates are x y width height ViewBox coordinates. In this case, the ViewBox starts at 0,0 and is 50 wide and 20 high. That is, the 500 x 200 pixel < SVG > element internally uses frames 50,20 from 0,0. In other words, each unit < SVG > in the coordinates used for the internal shape corresponds to a width of 500/50 = 10 pixels and a height of 200/20 = 10 pixels. That’s why the rectangle at x position 20 and Y position 10 is actually located at 200,100, and its width (10) and height (5) correspond to 100 and 50 pixels, respectively.

If the image is out of?

In the previous example, the aspect ratio of our viewBox is the same (500/200 = 50/20), but it may not be the same in practical application, so there may be three results: 1: Scale the graph by smaller size equal to full fill 2: scale the graph by larger size equal to full fill 3: Stretch or compress the shape so that it is completely viewport (meaning no aspect ratio at all, fitting the viewport is the first priority)

PreserveAspectRatio: This property allows us to specify how the scaled image is aligned relative to the viewport, and whether we want it to fit edges or clipping. PreserveAspectRatio = “(align [meet/Slice/none])”

The align value describe
xMin Align the left edge of the viewport
xMid Align with the horizontal center of the viewport
xMax Align with the right edge of the viewport
YMin Align with the top edge of the viewport
YMid Align with the vertical center of the viewport
YMax Align with the bottom edge of the viewport
Meet/Slice/none value describe
meet Preserve the aspect ratio and scale the ViewBox to fit the Viewport.
slice Preserve the aspect ratio and cut out any part of the image that doesn’t fit inside the Viewport.
none The width to height ratio is not retained. Scale the image so that the ViewBox fits the Viewport perfectly. The proportions are distorted.
Use:preserveAspectRatio="xMidYMid meet"/preserveAspectRatio="xMinYMin slice"

conclusion

SVG gives us a new way to imagine drawing. Although there are disadvantages, but this is not enough to negate its status. SVG technology is already a W3C recommendation. Its wide application in the field of map, high-precision graphics, portable graphics, data-driven responsive graphics also touches our ordinary People’s Daily life. It is also possible to provide high-quality output files with SVG in the printing world, with great control over cross-platform consistency. Because of these advantages, learning and using SVG can be very valuable, and there may be many interesting application scenarios to discover.

Recommendations forwriting

  • Interviewer series: Tell me what you understand about deep copy and light copy
  • Interviewer series: Tell me about the prototype, the prototype chain
  • Interviewer series: Please write an anti – shake or throttle function debounce/throttle
  • Please write instanceof by hand
  • 10 minutes quick handwriting implementation: Call /apply
  • 5 minutes quick handwriting implementation: bind
  • 5 minutes fast handwriting implementation: new

reference

  • The Essence of SVG (2nd Edition) — David Eisenberg & Amelia Bellamy-Royds
  • SVG — Flavio Copes
  • Getting started with SVG – How to write SVG by hand
  • SVG Research Path (23) – Understanding Viewports and viewboxes