1. Reasons for choosing a technology

“Only the shape, not the root”. This is my previous knowledge of SVG. SVG is not a new technology, but I have not mastered it. This is partly because it is rarely used in everyday work, and partly because drawing SVG is more expensive than asking a designer to provide UI.

To avoid the comfort zone and the desire for breakthroughs, I started looking for technical challenges on my own. As a result, learning SVG is on the agenda.

The reason why I chose SVG was that I had just done the UI reconstruction of the project, in which THE Icon component was fixed in the mind of using font Icon. Later, I thought about whether SVG could be used to draw and realize it, so I looked at the Ant Design code, and sure enough, Ant Design has replaced the font icon with an SVG icon.

// The advantage of using SVG ICONS for columns in Ant Design documents- Completely offline use, no need to download font files from THE CDN, ICONS will not display blocks due to network problems, and font files do not need to be deployed locally. - SVG has better sharpness on low-end devices. - Supports multi-color ICONS. - The replacement of built-in ICONS provides more APIS without style overwriting.Copy the code

Second, find the right path for you

2.1 Where there is learning, there is character

As an ordinary person who works hard, I sometimes fear that I still don’t achieve the result I want after working hard. Sometimes the worry is that you’ve spent time and energy researching a technology, but it’s not going to work, and you feel frustrated that it’s not going to work.

But as time went on, I found that what I had accumulated turned out to be a powerful tool to cope with my needs. As a result, I encountered a new technology, no longer hesitate to hesitate, rather than worrying all day long to learn too much, it is better to get it.

2.2 Which road leads to Rome

Sometimes I have such an illusion, I will read all the knowledge points, feeling not very difficult, feel that they will be. So one day after learning it, when I really need to use it, I have no idea how to do it.

All because of this technology has not reached the level of proficiency, just a simple familiarity with its content.

Which road will get me to Rome where I want to go? Through trial and error, I learned one of the secrets of learning, which is purposefully learning by doing.

When you wade through a technical document, you will remember very little and absorb even less. Come with a clear vision of where you want to be after learning a skill. For example, when SVG draws graphics, the basic graphics are simple, but the actual requirements are usually not so simple. So I went to its documentation with the specific features I had learned to implement. How do you identify specific functions for unfamiliar technologies? I would look for some mature and excellent websites to see what the technology has achieved and how it has been implemented. For example, ANTD has used SVG icon to replace the original font icon, there are a lot of graphics for my reference, I can learn while doing, but also check the reference answer.

So I found my way to Rome, where I wanted to go.

Live learning -SVG basics

Most of the knowledge of SVG is explained by MDN(developer.mozilla.org/zh-CN/docs/…).

3.1 the shape

introduce

SVG, or Scalable Vector Graphics, is an XML-based markup language for describing two-dimensional Vector Graphics. As a text-based open web standard, SVG can render graphics of different sizes elegantly and concisely, and it works seamlessly with other web standards such as CSS, DOM, JavaScript, and SMIL. In essence, SVG is to images what HTML is to text.

Basic elements

HTML provides elements that define headings, paragraphs, tables, and so on. Similarly, SVG provides elements for defining circles, rectangles, simple or complex curves. A simple SVG document consists of a root element and a basic shape element. There is also a G element, which organizes several basic shapes into a group.

From there, SVG can become more complex. SVG supports gradients, rotations, animations, filter effects, interaction with JavaScript, and more, but all of these additional language features need to be implemented within a defined graphics area.

Browser compatibility

All modern browsers support SVG, and in some cases even several versions. Can I Use has a fairly detailed list of browsers that support SVG, and Firefox 1.5 and later support portions of SVG, with increasing levels of support.

specification

1) SVG elements and attributes must be written in a standard format because XML is case sensitive (unlike HTML); 2) Attribute values in SVG must be enclosed in quotes, even for numeric values.

3.2 Coordinate Positioning

The grid

SVG draws graphics on top of the canvas it provides, using a coordinate system or grid system. This coordinate system is: the top left corner of the page is (0,0) coordinate point, coordinate in pixels, positive x direction is to the right, positive y direction is down.

<svg width='200' height='200' fill='# 555555'>
  <rect x='50' y='50' width='50' height='50' />
</svg>
Copy the code

In the picture below, I have marked the origin of the coordinates. The background is a 10*10 grid. It can be clearly seen that the drawn rectangle x base is 50 pixels from the origin, y base is 50 pixels from the origin, and its width and height are 50 pixels.

What is a pixel?

Basically, one pixel in an SVG document corresponds to one pixel on an output device, such as a display.

SVG also supports graphics scaling. SVG can define absolute sizes (for example, using “pt” or “cm” to identify dimensions), and SVG can also use relative sizes, simply by giving numbers, not units, and using the user’s units for output.

You can set the viewBox to zoom in and out:

<svg width='200' height='200' fill='# 555555' viewBox='0 0, 100, 100'>
  <rect x='50' y='50' width='100' height='100' />
</svg>
Copy the code

The viewBox property defines the area on the canvas that can be displayed: an area 100 wide and 100 high, starting at (0,0). This 100,100 area is going to be displayed on a 200 by 200 canvas. The effect is shown below, where the rectangle x is 100 pixels away from the origin, y is 100 pixels away from the origin, and its width and height are 100 pixels. This gives you double magnification.

User coordinate system

The mapping between user units and screen units is called the user coordinate system. In addition to scaling, the coordinate system can also rotate, tilt, and flip. The default user coordinate system 1 user pixel is equal to 1 pixel on the device (although the device may define exactly how big a pixel is). In SVG, where specific units of size are defined, such as “cm” or “in,” the resulting graphics are rendered at a 1:1 scale to the actual size.

3.3 Basic Shape

Different elements correspond to different shapes and use different attributes to define the size and position of the graph. Some shapes are a little redundant because they can be created from other shapes, but they are easy to use and make our SVG documents simple and understandable.

rectangular

The rect element can draw a rectangle.

<rect x="10" y="10" width="30" height="30"/>
<rect x="60" y="10" rx="5" ry="5" width="30" height="30"/>
Copy the code

It is not difficult to find that the graph on the right has rounded corners compared with the graph on the left, because the graph on the right is set with Rx and RY. Here are the six basic elements of a rectangle:

X: the x position in the upper left corner of the rectangle

Y: y position in the upper left corner of the rectangle

Width: indicates the width of the rectangle

Height: The height of the rectangle

Rx: radius of the x direction of the rounded corner

Ry: The y radius of the rounded corner

These six basic attributes control the position and shape of the rectangle on the screen.

circular

The circle element draws circles.

<circle cx='40' cy='40' r='20' />
Copy the code

The above code is displayed on the page as follows:

If you look closely, you’ll see that the center of the circle is at x:40 and y:40, which is what cx and cy do:

R: radius of the circle

Cx: the x position of the center of the circle

Cy: the y position of the center of the circle

The ellipse

Ellipse is a more general form of the circle element, and you can scale the x and y radii of the circle respectively (commonly known to mathematicians as the major and minor axis radii).

<ellipse cx='40' cy='40' rx='20' ry='10' />
Copy the code

The above code is displayed on the page as follows:

In contrast to a circle, an ellipse can be set with r and y radii, respectively. Note: When drawing an ellipse, both r radius and Y radius must be set, otherwise it will become a circle.

Rx: x radius of the ellipse

Ry: y radius of the ellipse

Cx: the x position in the center of the ellipse

Cy: y position at the center of the ellipse

line

Line Draws a straight Line. It takes the positions of two points as properties, specifying the starting and ending positions of the line.

<line x1='10' x2='50' y1='10' y2='50' />
Copy the code

The above code is displayed on the page as follows:

The line consists of two points, four elements that control its position and shape on the screen.

X1: the x position of the starting point

Y1: y position of the starting point

X2: the x position of the endpoint

Y2: the y position of the endpoint

Broken line

A Polyline is a set of straight lines joined together. Because it can have many points, all points of a polyline are placed in a points property:

<polyline points='10 10, 50 10, 50 50, 50 50, 90 50, 90 90, 90 90, 130 90, 130 130' />
Copy the code

The above code is displayed on the page as follows:

A polyline is controlled by a set of points to control its position and shape on the screen.

Points: indicates the number of points. Each number is separated by a white space, comma, terminator, or newline character. Each point must contain two numbers, one for the x coordinate and one for the y coordinate. So the list of points (0,0), (1,1), and (2,2) can be written like this: “0,0,1,1,2,2”.

polygon

Polygons are much like polylines in that they are made up of straight lines connecting a set of points. The difference is that polygon’s path automatically returns to the first point at the last point. Note that a rectangle is also a polygon, so if you need more flexibility you can create a rectangle out of a polygon.

/ / a star
<polygon points="50 25, 55 40, 70 40, 60 50, 65 65, 50 55, 35 65, 40 50, 30 40, 45 40"/>
/ / rectangle
<polygon points="100 20, 150 20, 150 70, 100 70"/>
Copy the code

The above code is displayed on the page as follows:

If you have a brush and start at a point, polygon lets you automatically go back to the starting point and complete a polygon.

Points: indicates the number of points. Each number is separated by a whitespace, comma, terminating command, or newline character. Each point must contain two numbers, one for the x coordinate and one for the y coordinate. So the list of points (0,0), (1,1), and (2,2) can be written like this: “0,0,1,1,2,2”. After the path is drawn, the graph closes, so the final line will be connected from position (2,2) to position (0,0).

3.4 the path

The element is the most powerful of SVG’s basic shapes. You can use it to create lines, curves, arcs, etc.

Path requires very few points to create smooth, fluid lines (like curves). Polyline elements can achieve a similar effect, but you have to set up a large number of points (the denser the points, the more contiguous they are, the smoother they look), and you can’t magnify them (when you zoom in, the points become more discrete). So a good understanding of paths is important when drawing SVG

3.4.1 Line Command

M

M is the x and y coordinates of the point you want to move to. The M command simply moves the brush, but does not draw a line. So the M command often appears at the beginning of a path to indicate where to start drawing.

L

The L command will draw a line segment between the current position and the new position (the point where the brush precedes L). L takes two arguments, the x and y coordinates of a point.

H

The H command draws a horizontal line. This command takes only one parameter, indicating the position to which it is moved on the x or y axis, because it moves in only one direction of the coordinate axis.

V

The V command draws a vertical line. This command takes only one parameter, indicating the position to which it is moved on the x or y axis, because it moves in only one direction of the coordinate axis.

Z

The Z command draws a line from the current point to the start of the path. The Z command is case insensitive.

The sample

<path d='M10 10 h 80 v 80 h -80 Z' fill='transparent' stroke='black' />
Copy the code

The path is as follows: move the brush to (10,10), start there, move 80 pixels to the right to form a horizontal line, then move 80 pixels down, then 80 pixels to the left, and then back to the starting point. The graph is as follows:

3.4.2 Curve Command

There are three commands for drawing smooth curves, two for drawing Bezier curves and one for drawing arcs, or parts of circles. There are many types of Bezier curves, but in the path element, there are only two: cubic Bezier curves C, and quadratic Bezier curves Q.

Bessel curve

The cubic Bezier curve needs to define one point and two control points, so using the C command to create the cubic Bezier curve, three sets of coordinate parameters need to be set:

C x1 y1, x2 y2, x y (or c dx1 dy1, dx2 dy2, dx dy)
Copy the code

S

The S command can be used to create Bessel curves as follows:

S x2 y2, x y (or s dx2 dy2, dx dy)
Copy the code

If the S command follows a C or S command, its first control point is assumed to be the central symmetry of the second control point on the previous command curve. If the S command is used alone, with no C or S command preceding it, the current point is used as the first control point.

<path d='M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80' stroke='black' fill='transparent' />
Copy the code

The effect is as follows:

Q

To create a quadratic Bessel curve, run the following command:

Q x1 y1, x y (or q dx1 dy1, dx dy)
Copy the code

It is simpler than cubic Bezier curves and requires only one control point to determine the slope of the curve at the beginning and end. So it requires two sets of parameters, control points and endpoint coordinates.

<path d='M10 80 Q 95 10 180 80' stroke='black' fill='transparent' />
Copy the code

The effect is as follows:

T

The T command creates a quadratic Bezier curve. The command is as follows:

T x y (or t dx dy)
Copy the code

The shortcut command T will infer a new control point from the previous control point. Note that the T command must be preceded by either a Q command or another T command to achieve this effect. If T is used alone, then the control point will be thought of as the same point as the end point, so a straight line will be drawn.

<path d='M10 80 Q 52.5 10, 95 80 T 180 80' stroke='black' fill='transparent' />
Copy the code

The effect is as follows:

A

The arc command A is another command to create an SVG curve. The command is as follows:

A rx ry x-axis-rotation large-arc-flag sweep-flag x y a rx ry x-axis-rotation large-arc-flag sweep-flag dx dy
Copy the code

Basically, an arc can be considered part of a circle or an oval. The first two parameters of the arc command A are the X-axis radius and the Y-axis radius respectively.

<path d="M10 315 L 110 215 A 30 50 0 0 1 162.55 162.45l 172.55 152.45a 30 50-45 0 1 215.1 109.9l 315 10" stroke="black" fill="green" stroke-width="2" fill-opacity="0.5"/>
Copy the code

The effect is as follows:

3.5 Fill and Border

Since it is a graph, the internal color and border properties can be changed.

3.5.1 track of coloring

The fill property sets the color inside the object. The stroke property sets the color of the line that draws the object. You can use CSS color naming schemes in HTML to define their colors, such as color names (like red), RGB values (like RGB (255,0,0)), hexadecimal values, rgba values, and so on.

<rect x="10" y="10" width="100" height="100" stroke="red" fill="#fff" fill-opacity="1" stroke-opacity="1" stroke-width='3'/>
Copy the code

The code above fills the rectangle with white and an opacity of 1. The border is 3 pixels wide, red in color and 0.5 in opacity. The stroke-opacity property controls the opacity of the stroke. The stroke-width property defines the width of the stroke.

3.5.2 stroke

stroke-width

It affects the stroke width.

stroke-linecap

It controls the shape of the border end, and it has three possible values:

Butt routinely ends a line segment with a straight edge, 90 degrees perpendicular to the direction of the stroke and running through its end.

Square works just as well, but slightly beyond the actual path, which is controlled by stroke-width.

Round indicates that the border ends at a rounded corner, and the radius of the rounded corner is also controlled by stroke-width.

stroke-linejoin

It controls how two stroke segments are connected.

It has three values available:

Miter is the default, which means using a square brush to form a sharp Angle at the join.

Round indicates that round corners are connected to achieve smooth effect.

Bevel, the joint will form a miter.

stroke-dasharray

It applies the dashed line type to the stroke edge.

<path d="M 10 75 Q 50 10 100 75 T 190 75" stroke="black" stroke-linecap="round" stroke-dasharray="Five,10,5" fill="none"/> <path d="M 10 75 L 190 75" stroke="red" stroke-linecap="round" stroke-width="1" stroke-dasharray="5, 5" fill="none"/>
Copy the code

The parameter to the stroke-dasharray property is a list of comma-separated numbers. For each set of numbers, the first is used to indicate the length of the colored area and the second is used to indicate the length of the uncolored area. So in the example above, the second path will fill in 5 pixels, followed by 5 blank units, and then 5 more. If you want a more complex dotted pattern, you can define more numbers.

other

There are also properties for padding and borders, including fill-rule, which defines how to color areas where graphics overlap; Stroke-miterlimit, which defines when to draw or not draw the miter effect of border connections; And stroke-dashoffset, which defines where the dotted line starts.

3.5.3 using CSS

In addition to defining the properties of the object, you can also style the fill and stroke using CSS. The syntax is the same as using CSS in HTML, except you change background-color and border to fill and stroke. Note that not all properties can be set with CSS. The coloring and filling parts can be set with CSS, such as fill, stroke, stroke-dasharray, etc., but not with gradients and patterns mentioned below. In addition, width, height, and path commands cannot be set with CSS. It is relatively easy to determine whether they can be set with CSS.

CSS can be inserted between lines of elements using the style property:

Or set a style paragraph. Just like in HTML, in SVG, in tags. Represents definitions, which define elements that do not appear in SVG graphics but can be used by other elements.

<? xml version="1.0" standalone="no"? ><svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1"> 
    <defs> 
        <style type="text/css">
       </style> 
    </defs> 
    <rect x="10" height="180" y="10" width="180" id="MyRect"/> 
</svg>
Copy the code

4. Use the -icon

I’ve picked a few groups of ICONS, and let’s go from simple to complex, and see how we can implement them based on what we’ve learned.

4.1 Forward and backward

Both ICONS are made up of lines and triangles. The drawing result is as follows:

The realization idea is to complete the drawing by the combination of straight lines and broken lines, the implementation code is as follows:

<svg width='2em' height='2em'>
    <line x1='10' y1='5' x2='10' y2='25' style='stroke: #5f5f5f; stroke-width: 3; '></line>
    <polyline points='24 5 10 15 24 25' fill='#5f5f5f'></polyline>{' '}
  </svg>
  <svg width='2em' height='2em'>
    <line x1='23' y1='5' x2='23' y2='25' style='stroke: #5f5f5f; stroke-width: 3; '></line>
    <polyline points='7 5 20 15 7 25' fill='#5f5f5f'></polyline>{'}</svg>
Copy the code

In the forward graph, the line starts (10,5) and ends (10,25) on the same X-axis, so the drawn line is vertical. The broken line, the starting point (24,5), the second point (10,15), and the end point (24,25) are drawn as a graph of an arrow that needs to be filled with color. Fill is controlled by using the fill property.

For a backward icon, the line is in the opposite position to the forward icon and the arrow is in the opposite direction.

4.2 Zoom in and out

These two ICONS are mainly made up of lines and circles. The drawing result is as follows:

The realization idea is to complete the drawing by the combination of line and circle, the implementation code is as follows:

<svg width='40' height='40'>
    <line x1='15' y1='9' x2='15' y2='21' style='stroke: #5f5f5f; stroke-width: 3; '></line>
    <line x1='9' y1='15' x2='21' y2='15' style='stroke: #5f5f5f; stroke-width: 3; '></line>
    <circle cx='15' cy='15' r='12' fill='transparent' stroke='#5f5f5f' stroke-width='2.5' />
    <line x1='24' y1='24' x2='and' y2='and' style='stroke: #5f5f5f; stroke-width: 3; '></line>
  </svg>
  <svg width='40' height='40'>
    <line x1='9' y1='15' x2='21' y2='15' style='stroke: #5f5f5f; stroke-width: 3; '></line>
    <circle cx='15' cy='15' r='12' fill='transparent' stroke='#5f5f5f' stroke-width='2.5' />
    <line x1='24' y1='24' x2='and' y2='and' style='stroke: #5f5f5f; stroke-width: 3; '></line>
  </svg>
Copy the code

Zoom in, vertical line starting point (15,9), end point (15,21), horizontal line starting point (9,15), end point (21,15), radius r of the circle is 12, the center of the circle is at the point (15,15), inclined line starting point (24,24), end point (29,29).

The only difference between a zoom icon and a zoom icon is that there are no vertical lines.

4.3 Back to top and back to bottom

These two ICONS are mainly composed of lines and arrows. The drawing result is as follows:

Drawing a graph through path requires more points to be drawn, making it relatively difficult to draw.

<svg width='2em' height='2em' fill='#5f5f5f'>
    <path d='M4 4.2l 28 4.2l 28 6 L 4 6Z M16 10.5l 19.5 15 L 16.7 15 L 16.7 27.5 L 15.3 27.5 L 15.3 15 L 12.5 15Z '></path>
  </svg>
  <svg width='2em' height='2em' fill='#5f5f5f'>
    <path d='M15.3 5.9l 15.3 18.4L 12.5 18.4L 16 22.8l 19.5 18.4L 16.7 18.4L 16.7 5.9z M4 28 L 4 26.2l 28.3 26.2l 28 28Z'></path>
  </svg>
Copy the code

As mentioned in the previous tip, the PATH element is one of the most powerful of the basic shapes of SVG. Just identify a starting point and you can draw the graph you want. For example, if you go back to the top and use the path element to draw the graph, put all the paths into the path element D and draw the path as follows:

1) starting from the upper left corner of the rectangle, use the M command, M4 4.2, to determine the starting point (4,4.2) and formally start drawing.

2) use the L command, L 28 4.2, to move along the X-axis to the point (4,4.2), thus completing a horizontal line.

3) Use the L command, L 28,6, to move along the Y-axis to the point (28,6), thus completing a vertical line.

4) Use the L command, L 4,6, to move along the X-axis to the point (4,6), thus completing a horizontal line.

5) using the Z command, the command draws a vertical line from the current point (4,6) to the starting point of the path (4,4.2). At this point, the rectangle is drawn.

6) Continue drawing the arrow shape, starting at the top of the arrow umbrella cap, using the M command, M16 10.6, to determine the starting point (16 10.6).

7) Use the L command, L 19.5 15, to move to the point (19.5,15), thus completing an inclined line.

8) Use the L command, L 16.7 15, to move along the X-axis to the point (16.7,15), thus completing a horizontal line.

9) Use the L command, L 16.7 27.5, to move along the Y-axis to the point (16.7,27.5), thus completing a vertical line.

10) Use the L command, L15.3 27.5, to move along the X-axis to the point (15.3,27.5), thus completing a horizontal line.

11) Use the L command, L 15.3 15, to move along the Y-axis to the point (15.3,15), thus completing a vertical line.

12) Using the L command, L 12.5,15, move along the X-axis to the point (12.5,15), thus completing a horizontal line.

13) using the Z command, the command draws a slanted line from the current point (12.5,15) to the starting point of the path (16,10.6). At this point, the arrow graph is drawn.

After drawing, you have a graph that goes back to the top, and you have a basic understanding of the path element and its line command.

4.4 exclamation point

I would like to introduce another way to draw exclamation marks, which is drawn by AI software. The drawing result is as follows:

The SVG icon provided by a designer colleague can be opened in the IDE to view the SVG code, such as this exclamation mark icon, which has the following SVG code:

<svg version='1.1' id='layer _1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0, 200, 200' style='enable-background: new 0 0 200 200' xml:space='preserve' width='40px' height='40px'>
    <path
      fill='#5f5f5f'
      d='M100 approximately 183.86 c to 15.18, 0-29.21-3.74-42.09-11.22 - s - 23.07-17.66-30.55-30.55 S16.14, 115.18, 16.14, 100 S3.74-29.21, 11.22-42.09 s17.66-23.07, 30.55 30.55 S84.82, 16.14, 100,16.14 s29.21, 3.74, 42.09, 11.22 s23.07, 17.66, 30.55, 30.55 S11.22, 26.92, 11.22, 42.09 s to 3.74, 29.21, 11.22, 42.09 s - 17.66, 23.07, 30.55, 30.55 S115.18, 183.86, 100183.86 z M100 approximately 49.72 C - 3.06, 0-5.68, 1.09-7.86, 3.28-2.18 c, 2.18-3.28, 4.8-3.28, 7.86 c0, 3.06, 1.09, 5.68, 3.28, 7.86 c2.18, 2.18, 4.8, 3.28, 7.86, 3.28 S5.68-1.09, 7.86-3.28 c2.18-2.18, 3.28, 4.8, 3.28-7.86 c0-3.06-1.09-5.68-3.28-7.86 C105.68, 50.81, 103.06, 49.72, 100,49.72 z M105.57, 94.43 C0-3.06-0.55-5.68-1.64-7.86 - s - 2.4-3.28-3.93-3.28 - c - 1.53, 0-2.84, 1.09, 3.93, 3.28-1.09 c, 2.18-1.64, 4.8-1.64, 7.86 l - 5.57, 50.28 C0, 3.06, 1.09, 5.68, 3.28, 7.86 c2.18, 2.18, 4.8, 3.28, 7.86, 3.28 s5.68-1.09, 7.86-3.28 c2.18-2.18, 3.28, 4.8, 3.28 7.86 L105.57, 94.43 z '
    />
  </svg>
Copy the code

For complex ICONS, if you have trouble drawing them, ask your designer colleagues to provide SVG files. The main consideration of the site to the graphics drawing quality requirements are higher, so we can adjust to local conditions.

Five, the summary

Back to our original intention, learning SVG is not only about understanding it, but also about being able to apply it to projects and solve problems.

If there was a real challenge, such as drawing complex SVG graphics from front-end code, I think I would be more confident that I could do it, rather than being clueless and helpless.

Another “truth” of technology practice, practice. Come on, with you.