Code optimization is always an eternal need of programmers, and the reasonable use of SVG images to replace some images in PNG/JPG and other formats is an important part of front-end optimization. Since it is optimization, let's first take a look at the SVG images. What are the advantages:
SVG can be read and modified by many tools (such as Notepad)
A few small examples of SVG images:
Let’s take a look at the code for the third share icon:
<svg xmlns=http://www.w3.org/2000/svg width=20 height=20 viewBox=0 0 20 20> <g stroke=#AAB0BA fill=none fill-rule=evenodd> <path d=M10 .524 3.413v8.235 stroke-linejoin=round/> <path d=M13.027 7.508c.813 0 1.678-.01 1.678-.01.449 0 .812.376.812.826l-.005 6.36a.819.819 0 0 1-.811.826H6.31a.822.822 0 0 1-.811-.826l.005-6.36c0-.456.36-.825.812-.825l1.689.006M8.373 5.111l2.143-2.09 2.143 2.07/> </g></svg>
Students who don’t understand SVG must have question marks on their faces now, just like the first time I met them. Don’t worry, let’s start from the basics.
What is SVG?SVG is an image format based on XML syntax, and its full name is Scalable Vector Graphics. Other image formats are based on pixel processing, and SVG is a description of the shape of an image, so it is essentially a text file with a small size and will not be distorted no matter how many times it is enlarged. In addition, SVG is a standard of the World Wide Web Consortium, and SVG is integrated with W3C standards such as DOM and XSL.
How to use?In HTML5, you can embed SVG elements directly into HTML pages, such as the little red heart above:
<body> <svg xmlns=http://www.w3.org/2000/svg xmlns:xlink=http://www.w3.org/1999/xlink width=20 height=20 viewBox=0 0 20 20> <defs> <rect id=ay=54 width=60 height=25 rx=1/> <mask id=bx=0 y=0 width=60 height=25 fill=#fff> <use xlink:href=#a/> </mask> </defs> <g transform=translate(-9 -56) fill=none fill-rule=evenodd> <use stroke= #EDEEEF mask=url(#b) stroke-width=2 xlink:href=#a/> <path d=M19.05 62.797c-.208-.268-1.776-2.188-3.629-1.725-.662.165-1.439.44-2.009 1.463-2.18 3.913 4.965 8.983 5.615 9.433V72l.023-.016.023.016v-.032c.65-.45 7.795-5.52 5.615-9.433-.57-1.023-1.347-1.298-2.009-1.463-1.853-.463-3.42 1.457-3.629 1.725z fill=red/> </g> </svg></body>
SVG code can also be written in a file ending with .svg, and then inserted into the web page using tags such as <img>
, <object>
, <embed>
, and <iframe>
.
<img src=search.svg><object id=object data=search.svg type=image/svg+xml></object><embed id=embed src=search.svg type=image/svg+xml><iframe id=iframe src=search.svg></iframe>
CSS can also use svg
.logo { background: url(logo.svg);}
SVG files can also be converted to BASE64 encoding and then written to web pages as Data URIs.
<img src=data:image/svg+xml;base64,[data]>SVG syntax
1. <svg>
tag
SVG code is placed in the top-level tag <svg>
. Below is an example.
<svg width=100% height=100%> <circle id=mycircle cx=50 cy=50 r=50 /></svg>
The width and height attributes of <svg>
specify the width and height of the SVG image in the HTML element. In addition to relative units, absolute units (unit: pixel) can also be used. If these two attributes are not specified, the default size of the SVG image is 300 pixels (width) x 150 pixels (height).
If you only want to display part of the SVG image, specify the viewBox attribute.
<svg width=100 height=100 viewBox=50 50 50 50> <circle id=mycircle cx=50 cy=50 r=50 /></svg>
The value of the <viewBox>
attribute has four numbers, which are the abscissa and ordinate of the upper left corner, the width and height of the viewport. In the above code, the SVG image is 100 pixels wide x 100 pixels high, and the viewBox attribute specifies that the viewport starts from the point (50, 50). So, what you actually see is the quarter circle in the lower right corner.
Note that the viewport must fit into the space it is in. In the above code, the size of the viewport is 50 x 50. Since the size of the SVG image is 100 x 100, the viewport will be enlarged to fit the size of the SVG image, that is, it will be enlarged four times.
If you do not specify the width attribute and height attribute and only specify the viewBox attribute, it is equivalent to giving only the aspect ratio of the SVG image. In this case, the default size of the SVG image will be equal to the size of the HTML element it contains.
2. <circle>
tag
The <circle>
tag represents a circle.
<svg width=300 height=180> <circle cx=30 cy=50 r=25 /> <circle cx=90 cy=50 r=25 class=red /> <circle cx=150 cy=50 r=25 class =fancy /></svg>
The code above defines three circles. The cx, cy, and r attributes of the <circle>
tag are the abscissa, ordinate, and radius respectively, and the unit is pixels. The coordinates are relative to the origin of the upper left corner of the <svg>
canvas.
The class attribute is used to specify the corresponding CSS class.
.red { fill: red;}.fancy { fill: none; stroke: black; stroke-width: 3pt;}
SVG's CSS properties are different from those of web elements.
fill: fill color
stroke: stroke color
stroke-width: border width
3. <line>
tag
The <line>
tag is used to draw straight lines.
<svg width=300 height=180> <line x1=0 y1=0 x2=200 y2=0 style=stroke:rgb(0,0,0);stroke-width:5 /></svg>
In the above code, the x1 attribute and y1 attribute of the <line> tag represent the abscissa and ordinate coordinates of the starting point of the line segment; the x2 attribute and y2 attribute represent the abscissa and ordinate coordinates of the end point of the line segment; the style attribute represents the style of the line segment.
4. <polyline>
tag
The <polyline>
tag is used to draw a polyline.
<svg width=300 height=180> <polyline points=3,3 30,28 3,53 fill=none stroke=black /></svg>
The points attribute of <polyline>
specifies the coordinates of each endpoint. The abscissa and ordinate are separated by commas, and points are separated by spaces.
5. <rect>
tag
The <rect>
tag is used to draw rectangles.
<svg width=300 height=180> <rect x=0 y=0 height=100 width=200 style=stroke: #70d5dd; fill: #dd524b /></svg>
The x attribute and y attribute of <rect>
specify the abscissa and ordinate coordinates of the upper left corner endpoint of the rectangle; the width and height attributes specify the width and height (unit pixels) of the rectangle.
6. <ellipse>
tag
The <ellipse>
tag is used to draw ellipses.
<svg width=300 height=180> <ellipse cx=60 cy=60 ry=40 rx=20 stroke=black stroke-width=5 fill=silver/></svg>
The cx attribute and cy attribute of <ellipse>
specify the abscissa and ordinate coordinates of the ellipse center (unit pixels); the rx attribute and ry attribute specify the radii of the ellipse's transverse and longitudinal axes (unit pixels).
7. <polygon>
tag
The <polygon>
tag is used to draw polygons.
<svg width=300 height=180> <polygon fill=green stroke=orange stroke-width=1 points=0,0 100,0 100,100 0,100 0,0/></svg>
The points attribute of <polygon>
specifies the coordinates of each endpoint. The abscissa and ordinate are separated by commas, and points are separated by spaces.
8. <path>
tag
The <path>
tag is used to specify the path.
<svg width=300 height=180><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></svg >
The d attribute of <path>
represents the drawing order. Its value is a long string. Each letter represents a drawing action, followed by coordinates.
M: move to (moveto)
L: Draw a straight line to (lineto)
Z: closed path
9. <text>
tag
The <text>
tag is used to draw text.
<svg width=300 height=180> <text x=50 y=25>四客足球</text></svg>
The x and y attributes of <text>
represent the abscissa and ordinate of the starting point of the text block's baseline. The style of text can be specified using the class or style attributes.
10. <use>
tag
The <use>
tag is used to copy a shape.
<svg viewBox=0 0 30 10 xmlns=http://www.w3.org/2000/svg> <circle id=myCircle cx=5 cy=5 r=4/> <use href=#myCircle x=10 y =0 fill=blue /> <use href=#myCircle x=20 y=0 fill=white stroke=blue /></svg>
The href attribute of <use>
specifies the node to be copied, and the x attribute and y attribute are the coordinates of the upper left corner of <use>
. In addition, you can also specify width and height coordinates.
11. <g>
tag
The <g>
tag is used to group multiple shapes into a group for easy reuse.
<svg width=300 height=100> <g id=myCircle> <text x=25 y=20>circle</text> <circle cx=50 cy=50 r=20/> </g> <use href =#myCircle x=100 y=0 fill=blue /> <use href=#myCircle x=200 y=0 fill=white stroke=blue /></svg>
12. <defs>
tag
The <defs>
tag is used for custom shapes. The code inside it will not be displayed and is for reference only.
<svg width=300 height=100> <defs> <g id=myCircle> <text x=25 y=20>circle</text> <circle cx=50 cy=50 r=20/> </g> </defs> <use href=#myCircle x=0 y=0 /> <use href=#myCircle x=100 y=0 fill=blue /> <use href=#myCircle x=200 y=0 fill=white stroke=blue /></svg>
13. <pattern>
tag
The <pattern>
tag is used to customize a shape that can be referenced to tile an area.
<svg width=500 height=500> <defs> <pattern id=dots x=0 y=0 width=100 height=100 patternUnits=userSpaceOnUse> <circle fill=#bee9e8 cx=50 cy=50 r=35 /> </pattern> </defs> <rect x=0 y=0 width=100% height=100% fill=url(#dots) /></svg>
In the above code, the <pattern>
tag defines a circle as a dots pattern. patternUnits=userSpaceOnUse
means that the width and length of <pattern>
are actual pixel values. Then, assign this mode to fill the lower rectangle.
14. <image>
tag
The <image>
tag is used to insert image files.
<svg viewBox=0 0 100 100 width=100 height=100> <image xlink:href=path/to/image.jpg width=50% height=50%/></svg>
In the above code, xlink:href
attribute of <image>
indicates the source of the image.
15. <animate>
tag
The <animate>
tag is used to produce animation effects.
<svg width=500px height=500px> <rect x=0 y=0 width=100 height=100 fill=#feac5e> <animate attributeName=x from=0 to=500 dur=2s repeatCount=indefinite /> </rect ></svg>
In the above code, the rectangle will continue to move and produce animation effects.
The attributes of <animate>
have the following meanings.
attributeName: The name of the attribute where the animation effect occurs.
from: The initial value of a single animation.
to: The end value of a single animation.
dur: the duration of a single animation.
repeatCount: animation loop mode.
Animations can be defined on multiple properties.
<animate attributeName=x from=0 to=500 dur=2s repeatCount=indefinite /><animate attributeName=width to=500 dur=2s repeatCount=indefinite />
16. <animateTransform>
tag
The <animate>
tag has no effect on the CSS transform attribute. If transformation is required, the <animateTransform> tag must be used.
<svg width=500px height=500px> <rect x=250 y=250 width=50 height=50 fill=#4bc0c8> <animateTransform attributeName=transform type=rotate begin=0s dur=10s from=0 200 200 to=360 400 400 repeatCount=indefinite /> </rect></svg>
In the above code, the effect of <animateTransform>
is rotation. At this time, the from and to attribute values have three numbers. The first number is the angle value, and the second and third values are the coordinates of the rotation center. from=0 200 200 means that at the beginning, the angle is 0, and the rotation starts around (200, 200); to=360 400 400 means that at the end, the angle is 360, and the rotation starts around (400, 400).
1. DOM operations
If the SVG code is written directly in the HTML web page, it becomes part of the web page's DOM and can be directly manipulated using the DOM.
<svg id=mysvg xmlns=http://www.w3.org/2000/svg viewBox=0 0 800 600 preserveAspectRatio=xMidYMid meet> <circle id=mycircle cx=400 cy=300 r=50 /><svg>
After the above code is inserted into the web page, you can use CSS to customize the style.
circle { stroke-width: 5; stroke: #f00; fill: #ff0;}circle:hover { stroke: #090; fill: #f8f8f8;}
The SVG can then be manipulated with JavaScript code.
var mycircle = document.getElementById('mycircle');mycircle.addEventListener('click', function(e) { console.log('circle clicked - enlarging'); mycircle.setAttribute('r', 60);}, false);
The above code specifies that if the graphic is clicked, the r attribute of the circle element will be rewritten.
2. Get SVG DOM
Use <object>
, <iframe>
, <embed>
tags to insert SVG files to obtain SVG DOM.
var svgObject = document.getElementById('object').contentDocument; var svgIframe = document.getElementById('iframe').contentDocument; var svgEmbed = document.getElementById('embed').getSVGDocument();
Note that if you use the <img> tag to insert an SVG file, you cannot get the SVG DOM.
3. Read SVG source code
Since the SVG file is a piece of XML text, the SVG source code can be read by reading the XML code.
<div id=svg-container> <svg xmlns=http://www.w3.org/2000/svg xmlns:xlink=http://www.w3.org/1999/xlink xml:space=preserve width=500 height=440 > <!-- svg code --> </svg></div>
Use the serializeToString() method of the XMLSerializer instance to obtain the code of the SVG element.
var svgString = new XMLSerializer() .serializeToString(document.querySelector('svg'));
4. Convert SVG image to Canvas image
First, you need to create a new Image object and assign the SVG image to the src attribute of the Image object.
var img = new Image();var svg = new Blob([svgString], {type: image/svg+xml;charset=utf-8});var DOMURL = self.URL || self.webkitURL || self; var url = DOMURL.createObjectURL(svg);img.src = url;
Then, when the image is loaded, draw it to the <canvas>
element.
img.onload = function () { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0);};summary
SVG can do much more than that. We will explain the animation effects and text effects made using SVG in detail later, but let’s stop here today.
console.log('右下角点好看呦')
The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will support Script Home.