1. What is SVG?

SVG is an image file format that stands for Scalable Vector Graphics. Xml-based markup language.

1.1 What is image file format?

To take a few familiar 🌰 examples:

The commonly used image formats are WebP, GIF, PNG, etc. SVG is one of them.

1.2 What is a vector diagram? What other diagrams are there besides vector diagrams?

A vector is also called a vector

  • Graphic elements (points and lines) in vector graphics are called objects, and each object is a single individual with attributes such as size, orientation, outline, color, and screen position.
  • Simply put, vector graphics software uses mathematical methods to draw basic shapes such as rectangles.

Vector graph features:

  1. Vector graphics can reproduce clear Outlines, lines are very smooth, and has good scaling;
  2. Because the information stored in the image is line and graph block, has nothing to do with the resolution and graph size, only with the complexity of the image, so the image file occupies a small storage space;
  3. In addition, text editing ability is strong
  4. Compared with bitmaps, display and print are much faster; Graphics are not real and vivid, and colors are not rich.

Bitmaps, also known as Raster graphics, are images (physical representations of human visual perception) represented by pixel arrays (consisting of multiple basic pixel units repeated in horizontal and vertical directions). (Explanation from Wikipedia)

Bitmap features:

  1. Bitmap pixels are assigned specific positions and color values.
  2. The color information for each pixel is combined by RGB (RGBColor mode is a color standard in the industry. It is a kind of gray value representation of various colors through the changes of red (R), green (G), blue (B) color channels and their superposition among each other.

Examples of the display effect of vector graphics :(a) original vector graphics; (b) 8 times magnification of vector image; (c) 8-fold bitmap magnification. Bitmaps have poor magnification quality, but vector maps can be magnified indefinitely without loss of quality.

1.3 What is XML Markup Language?

Extensible Markup Language (XML) is a Markup Language. Mark refers to the information symbol that can be understood by the computer. Through this mark, the computer can process articles containing various information.

<message>
    <warning>
         Hello World
    </warning>
</message>
Copy the code

Now that we have a general idea of what SVG is, how to use it

2. How do I use SVG?

2.1 Basic structure of SVG

<svg width='440' height='170' xmlns='http://wwww.w3.org/2000/svg'>
     <title>Cat</title>
     <desc>Stick Figure of Cat</desc>
     <circle cx="100" cy="100" r="50">
        <title>I'm the title of the circle</title>
     </circle>
</svg>
Copy the code
  • SVGimageThe default sizeIt’s 300 pixels wide x 150 pixels high,<svg>Defines the entire image in pixelswidthheight
  • xmlnsThe property definesSVGNamespace of
  • <title>The contents of the element can be displayed by the reader on the title bar or as a hint when the mouse pointer points to the image
  • The element allows us to define a complete description of the image
  • Inside the tag, it is not possible to use normal HTML tags, such as:
<svg width='140' height='170' xmlns='http://wwww.w3.org/2000/svg'>
   <span>123</span>
</svg>
Copy the code

2.2 viewBox, viewPort, and preserveAspectRatio

If you want to show only a portion of an SVG image, specify the viewBox property

<svg width="100" height="100" viewBox="0 0 100 100">
    <circle id="mycircle" cx="50" cy="50" r="50" />
</svg>
Copy the code

Let’s scale:

<svg width="100" height="100" viewBox="0 0 50 to 50." ">
    <circle id="mycircle" cx="50" cy="50" r="50" />
</svg>
Copy the code

From the point of view of 0,0, it’s 4 times bigger.

Difference between viewPort and viewbox

  1. Viewport The viewport is equivalent to the display screen.
  2. A viewbox is a close-up of a small piece of the screen that is zoomed in on the entire screen
  3. PreserveAspectRatio Specifies the alignment and scaling of a viewbox to a viewport.
  • The viewPort towidth="10cm" height="10cm"
<svg width="10cm" height="10cm" style={{border: '1px solid #Awesome!', backgroundColor: 'pink'}} >
          <rect x="50" y="100" width="50" height="50"
                stroke="# 000000" fill="black"/>
          <rect x="100" y="100" width="50mm" height="50mm"
                stroke="# 000000" fill="# 666" />
</svg>
Copy the code

<svg width="500" height="75" viewBox="0 0 250 75" preserveAspectRatio="xMinYMin slice"
            style={{border: "1px solid #cccccc}} ">
    <rect x="1" y="1" width="50" height="50" style={{stroke: "red", fill: "none}} "/ >
</svg>
Copy the code

PreserveAspectRatio controls the scaling ratio. The preserveAspectRatio property takes two values separated by Spaces.

  • The first value tells the ViewBox how to align within the Viewport. The value itself consists of two parts.
  • The second value indicates how the aspect ratio, if any, is preserved

Scale is used to scale elements, and can also be used to scale SVG. Here’s how it looks:

  • Scale is the scaling of SVG itself as well as elements within it. And the reference position is the center point
< SVG width="100" height="100" transform="scale(0.7,1)" style={{border: "1px solid # CCCCCC ", marginLeft: '20px'}}> <rect x="1" y="1" width="50" height="50" style={{stroke: "red", fill: "none"}} /> </svg> <br/> <svg width="100" height="100" style={{border: "1px solid #cccccc"}}> <rect x="1" y="1" width="50" height="50" style={{stroke: "red", fill: "none"}} /> </svg>Copy the code

2.3 Common Graphics

  1. <circle>

I already mentioned that point(cx, cy)That’s where the center of the circle is,rRepresents the radius of the circle

Properties: Stroke is the outline color, fill is the fill color, strokeWidth is the width of the outline these properties are also common in other graphics

<circle cx='55' cy='80' r='25' stroke='black' fill='pink' strokeWidth='8'/>
Copy the code

Application, as a debit identifier for subtraction, e.g. :

  1. <line>

The point (x1, y1) is the starting point, and (x2, y2) is the ending point. The stroke attribute must be added otherwise the line cannot be drawn 🙈

For applications, slash 0:

  1. <path>

The element contains five commands to draw a line, and the line command is to draw a line between two points. The first is the “Move to” command, M, which takes two arguments, the X-axis and Y-axis coordinates of the point to Move to.

<svg width="200px" height="200px" >
  <path d="M10 10"/>
  <circle cx="10" cy="10" r="2" fill="red"/>
</svg>
Copy the code

Render to find only one point, so the M command moves the brush position, but does not draw a line.

In fact, there are three commands that can actually draw a Line. The most common is the “Line to” command, L,

Direction control command: H, draw horizontal lines; V, draw a vertical line.

<path d="M10 10 H 90 V 90 "/>
Copy the code
<path d="M10 10 H 90 V 90 H 10" fill="pink"/>
Copy the code
<path d="M10 10 H 90 V 90 H 10 " fill="transparent" strokeWidth="2" stroke="black"/>
Copy the code
<path d="M10 10 H 90 V 90 " fill="transparent" strokeWidth="2" stroke="black"/>
<line x1={90} y1={90} x2={10} y2={10} stroke="black" strokeWidth="2" />
Copy the code
<path d="M 18,3 L 46,3 L 46,40 L 61,40 L 32,68 L 3,40 L 18,40 Z"></path>
Copy the code

The famous Bezier curve

Cubic curve, C is a slightly more complicated curve. Each control point of a cubic Bezier curve has two control points

C > x1 > y1, > x2 > y2, > x > y (or) > C > dx1 > dy1, > dx2 > dy2, > dx > dy X1,y1 is the control point of the starting point, and x2,y2 is the control point of the ending point.

Application: Divide the vertical curve

For more details: developer.mozilla.org/en-US/docs/…

  1. <polygon>

Draw a polygon

<polygon fill="transparent" stroke="orange" stroke-width="3" points="0,0 50,0 100,100 0,100,0"/>
Copy the code
  1. <text>The text
<text x="50" y="85"  fontSize="35">8</text>
Copy the code

<text x="50" y="85" textAnchor="middle" fontSize="35">8</text>
<line x1={10} y1={85} x2={100} y2={85} stroke="yellow"/>
<line x1={50} y1={150} x2={50} y2={0} stroke="green"/>
Copy the code

8

When calculating the up-down spacing, you can use the attributes alignmentBaseline and textAnchor to set the baseline for the number

  1. <animate>animation
  • AttributeName: The name of the attribute on which the animation effect occurs.
  • From: Initial value of a single animation.
  • To: End value of a single animation.
  • Dur: Duration of a single animation.
  • RepeatCount: The cyclic mode of the animation.
<rect x="0" y="0" width="100" height="100" fill="#feac5e">
    <animate attributeName="x" from="0" to="500" dur="2s"
    repeatCount="indefinite" />
</rect>
Copy the code
  1. <defs>For custom shapes

Its internal code is not displayed

<path d="M12.7627 1.68984 C13.3585 0.820476 14.6415 0.820475 15.2373 1.68983L18.8282 6.92945C19.1533 7.40377 19.632 7.75154 20.1835 7.91413L26.2764 9.71018C27.2873 10.0082 27.6838 11.2284 27.0411 12.0637L23.1676 17.098C22.8169 17.5537 22.6341 18.1164 22.6499 18.6912L22.8245 25.0409C22.8535 26.0944 21.8155 26.8485 20.8225 26.4954L14.8376 24.3672C14.2958 24.1745 13.7042 24.1745 13.1624 24.3672L7.17748 26.4954C6.18447 26.8485 5.1465 26.0944 5.17548 25.0409L5.35011 18.6912C5.36592 18.1164 5.18309 17.5537 4.83244 17.098L0.958931 12.0637C0.316237 11.2284 0.712704 10.0082 1.72363 9.71018L7.81646 7.91413C8.36802 7.75154 8.84668 7.40377 9.17175 6.92945L12.7627 1.68984Z"
   fill="url(#paint0_linear)"
   stroke="url(#paint1_linear)"
/>
            <defs>
                <linearGradient
                    id="paint0_linear"
                    x1="14"
                    y1="1"
                    x2="14"
                    y2="31"
                    gradientUnits="userSpaceOnUse"
                >
                    <stop stopColor="#FFF7E8" />
                    <stop offset="1" stopColor="#FFA900" />
                </linearGradient>
                <linearGradient
                    id="paint1_linear"
                    x1="14"
                    y1="1"
                    x2="14"
                    y2="31"
                    gradientUnits="userSpaceOnUse"
                >
                    <stop stopColor="#FFA900" />
                    <stop offset="1" stopColor="#FFA900" stopOpacity="0" />
                </linearGradient>
            </defs>
</svg>
Copy the code
  • The gradient:linearGradientThe element defines a linear gradient for filling or stroke of graphic elements.
    • Linear gradient

    • Radial gradient

Developer.mozilla.org/zh-CN/docs/…

More visible graphic objects: www.ruanyifeng.com/blog/2018/0…

  1. <image>
<ellipse cx='154' cy='154' rx='150' ry='120' style='fill: #999'/>  
<ellipse cx='152' cy='152' rx='150' ry='120' style='fill: #999' />   
<image xlink:href='img.src' x='72' y='92'    width='160' height='120'  />
Copy the code
  1. <use>reuse
<svg width="200" height="200" transform="Scale (0.4, 0.4)"
            style={{border: "3px solid #999}} ">
        <defs>
          <g id="Port">
            <circle style={{fill:"pink"}} r="10"/>
          </g>
        </defs>
        <use x="50" y="45" href="#Port" />
        <use x="70" y="89" href="#Port" />
</svg>
Copy the code

  1. <g>grouping
<g stroke="black" fill="pink" stroke-width="5">
              <circle cx="50" cy="35" r="25"/>
              <circle cx="75" cy="35" r="25"/>
              <circle cx="150" cy="35" r="25"/>
              <circle cx="125" cy="35" r="25"/>
              <circle cx="100" cy="35" r="25"/>
 </g>
Copy the code

Note: SVG renders in the exact order in which the elements are defined, unlike HTML, which relies on z-index values to control layering. In SVG, elements written before are rendered first, and elements written after are rendered. Post-rendered elements overwrite the previous ones, although sometimes they don’t appear to be overwritten due to transparency, but SVG does render in strict order.

2.2 Using SVG Files

  1. Become part of the DOM

Then you do it with JavaScript and CSS

<! DOCTYPEhtml>
    <html>
        <head></head>
        <body>
            <svg
              id="mysvg"
              xmlns="[http://www.w3.org/2000/svg](http://www.w3.org/2000/svg)"
              viewBox="0 0 800 600"
              preserveAspectRatio="xMidYMid meet">
            <circle id="mycircle" cx="400" cy="300" r="50" />
            <svg>
        </body>
    </html>
Copy the code
  1. Img

<img src="apple.svg" />

There are many limitations to interactivity using this approach, such as the inability to use JS controls.

  1. Background-image

One caveat to using the background image method: Try not to format SVG images using base64 encoding, because it blocks downloads of other resources while loading.

background-image: url(bblogo.svg);

Iframe, embed and other tags can also be used

There is also a commonly used drawing tool in the working scene: Canvas.

3. How does it compare to Canvas?

3.1 Script Drawing

var canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(75.50);
    ctx.lineTo(100.75);
    ctx.lineTo(100.25);
    ctx.fill();
    //ctx.fill();
}
Copy the code

ctx.beginPath();
    ctx.arc(75.75.50.0.Math.PI * 2.true); / / to draw
    ctx.moveTo(110.75);
    ctx.arc(75.75.35.0.Math.PI, false);   // Mouth (clockwise)
    ctx.moveTo(65.65);
    ctx.arc(60.65.5.0.Math.PI * 2.true);  / / the left eye
    ctx.moveTo(95.65);
    ctx.arc(90.65.5.0.Math.PI * 2.true);  / / in the right eye
    ctx.stroke();
Copy the code

3.2 the gradient

Color fill

function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');
    for (var i=0; i<6; i++){for (var j=0; j<6; j++){ ctx.strokeStyle ='rgb(0,' + Math.floor(255-42.5*i) + ', ' + 
                         Math.floor(255-42.5*j) + ') ';
        ctx.beginPath();
        ctx.arc(12.5+j*25.12.5+i*25.10.0.Math.PI*2.true); ctx.stroke(); }}}Copy the code

3.3 summary

svg canvas
SVG is essentially a language for describing 2D graphics using XML <canvas>It is just a canvas and does not have the ability to draw itself. Drawing must use scripting languages such as JavaScript.
Object – based scalable vector graphics that do not distort no matter how much magnification. Canvas is based on pixel rendering, reduce distortion.
It can be inserted directly into a web page and controlled with CSS and JS. So event handlers are supported. Each element is a separate DOM element, since it’s a separate DOM element Canvas is just an HTML element, and graphics in it do not create separate DOM elements. Therefore, we cannot manipulate individual graphics in the Canvas through JavaScript or monitor specific graphics.
Not suitable for game applications Best suited for graphics-intensive games, where many objects are frequently redrawn
Cannot save the resulting image as.png or.jpg; Cannot import.png or.jpg images Can save the resulting image in.png or.jpg format; Ability to import.png or.jpg images

4. Development experience sharing

4.1 SVG is easy to locate

{zeroArr.length && zeroArr.map((num, idx) = > (
   <SVGPath
      alignmentBaseline="middle"
      key={`text-The ${idx} `}d={`M x0 y0 L .`}
      filltype={theme.color.slash}
      strokeWidth="1"
    />
))}
Copy the code

If you implement it with plain CSS and HTML, you’re out of document flow

<span style="position: relative;">
    <span>22</span>
    <svg width="18.703125" height="18" style="position: absolute; left: 0px; top: 0px;">
        <line x1="0" y1="5" y2="15" stroke="# 666" stroke-width="1.2" x2="18.703125">
        </line>
    </svg>
</span>
Copy the code

4.2 Combined rendering

  • At present, some questions in the text solution do not contain: power, fraction, underline, small stars, broken lines and other special processing symbols, available HTML tags to render, convenient development

  • If you have these special graphics, find the appropriate way to render them depending on the situation, but when rendering text, it is best not to mix SVG with HTML tags, because different sizes will appear on different ends. For example:

4.3 SVG does not fold lines and can be scaled

Because the screen size on the device is different, the zoom effect can be adjusted according to the device size

4.4 SVG text is optional and searchable

PNG and Canvas cannot be searched.

4.5 Sprite drawing in SVG

  • SVG Sprite art technique = PNGs to make Sprite art
  • Advantage: No extra 2x graphics needed for HD screens. Because SVG is resolution-independent, SVG can be displayed cleanly on any device. And using SVG also saves HTTP requests.
  • There are two ways to do this:
    • Define all ICONS using elements in SVG code and hide it. Use the element to reference it via xlink:href=”#id”
    • Use the VIEWbox property of SVG to specify the area of the SVG canvas to display, following the background-position principle.

4.6 Volume Optimization

  • Remove unwanted attributes from SVG and you will see a steady increase in performance

Tools: github.com/svg/svgo

4.7 Handling degradation

  • Most modern browsers support SVG.
  • Supporting older browsers such as IE8 requires downgrading, which means using PNGs for display on browsers that do not support SVG.

4.8 SVG and Media Query

Change the SVG style by device features, if used in styles in embedded SVG files to media queries.

<html>
<head>
    <title>Canvas tutorial</title>
    <style type="text/css">
        circle {
            stroke: # 000;
            stroke-width: 30;
            fill: # 009688;
        }
        @media (max-width: 500px) {
            circle {
                fill: #673ab7; }}@media (min-width:500px) {
            circle {
                fill: #ffc107; stroke: pink; }}</style>
</head>
<body onload="draw();">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
     x="0" y="0" viewBox="- 20-20, 250, 250" xml:space="preserve">
    </defs>
    <circle cx="100" cy="100" r="100" />
    <circle cx="100" cy="100" r="50" />
    <rect height="50" width="50" fill="green" x="75" y="75"/>
</svg>
<svg x="50" y="50" width="500" height="500">
    <circle cx="150" cy="150" r="100" fill="# 009688"/>
    <circle cx="150" cy="150" r="50" />
    <rect height="50" width="50" fill="green" x="125" y="125"/>
</svg>
</body>
</html>
Copy the code

5. References

Developer.mozilla.org/zh-CN/docs/… www.cnblogs.com/tugenhua070… Juejin. Cn/book / 684473… www.sarasoueidan.com/blog/struct… Css-tricks.com/understandi… Svgontheweb.com/zh/#resourc…

❤️ Thank you

That is all the content of this sharing. I hope it will help you

Don’t forget to share, like and bookmark your favorite things.