Author: Concave-man – Nuan Nuan

SVG stands for Scalable Vector Graphics and uses XML format to define Graphics.

First, SVG impression

SVG is widely used, thanks to its powerful features.

1.1, vector

Draw the outline of Shenzhen Subway by using the features of SVG vector:

1.2, iconfont

SVG can be converted to iconfont according to certain rules:

1.3、 foreignObject

ForeignObject inserts HTML elements in SVG:

<svg xmlns="http://www.w3.org/2000/svg">
	<foreignObject width="120" height="60">
		<p style="font-size:20px; margin:0;"</p> </foreignObject> </ SVG >Copy the code

Screenshot implementation process:

  1. Start by declaring a basic SVG template that requires some basic description information and, most importantly, it has<foreignObject></foreignObject>This pair of labels;
  2. Embed the DOM template template to be renderedforeignObjectCan;
  3. usingBlobBuild SVG objects;
  4. usingURL.createObjectURL(svg)Remove URL.

1.4, SVG SMIL

Since wechat editor does not allow the embedding of

Click “Bump Laboratory”, rotate 360 degrees around the center of “Bump Laboratory”, click 0.5 seconds after the emergence of AOtu. IO /, animation only run once.

Below is a GIF loop demo:

The code is as follows:

<svg width="360" height="300" xmlns="http://www.w3.org/2000/svg">
    <g>
        <! -- Run the transform rotation animation with restart="never" -->
        <animateTransform attributeName="transform" type="rotate" begin="click" dur="0.5 s" from="0, 100, 80" to="360, 100, 80"  fill="freeze" restart="never" />
        <g>
            <text font-family="microsoft yahei" font-size="20" x="50" y="80">Convex laboratory</text>
        </g>
        <g style="opacity: 0;">
            <! -- Same initial position and approximate width and height, trigger click event -->
            <text font-family="microsoft yahei" font-size="20" x="50" y="80">https://aotu.io/</text>
            <! -- Run transform animation to change the position of the text -->
            <animateTransform attributeName="transform" type="translate" begin="click" dur="0.1 s" to="0 40." "  fill="freeze" restart="never" />
            <! -- Click to run opacity animation after 0.5 seconds -->
            <animate attributeName="opacity" begin=Click + 0.5 "s" from="0" to="1" dur="0.5 s" fill="freeze" restart="never" />
        </g>
    </g>
</svg>
Copy the code

This is my general impression of SVG, and recent requirements development has renewed my knowledge that SVG implements unscaling and applets do not support processing of SVG tags. Let me tell you about it below.

2. SVG implements unproportional scaling

Iconfont, as we know it, can be scaled by changing the font size, but this is scaling. How do you achieve unscaling SVG? As shown below, how do you scale a rabbit out of scale?

Key points: The realization of non-proportional scaling mainly involves three knowledge points: Viewport, viewBox, and preserveAspectRatio. Viewport and viewBox can be used to scale, and viewBox and preserveAspectRatio can be used to scale.

2.1, the viewport

Viewport indicates the size of the SVG visible area. Viewport is like our monitor screen size, hidden outside the area, origin in the upper left corner, X-axis horizontal right, Y-axis vertical down.

Specify the view size with csS-like properties width and height:

<svg width="400" height="200"></svg>
Copy the code

2.2, viewBox

ViewBox values have 4 numbers: x, y, width, height. X: top left abscissa, y: top left abscissa, width: width, height: height By default, the origin is in the upper left corner, X-axis horizontally to the right, Y-axis vertically down.

<svg width="400" height="200" viewBox="0 0 200 100"></svg>
Copy the code

The screen of the monitor screen, can be close-up, can be panoramic, this is the viewBox. The viewBox can be thought of as the box selected by the screenshot tool, and the viewPort effect is to display the screenshot contents of the box again in full screen on the monitor.

SVG Research Path (23) – Understanding Viewports and viewboxes

2.3, preserveAspectRatio

The red and blue boxes in the figure above happen to be in the same proportion as the monitor. If it is the green box in the figure below, how will it be displayed on the monitor screen?

2.3.1, definitions,

PreserveAspectRatio functions as a viewBox and can be used as follows:

preserveAspectRatio="[defer] <align> [<meetOrSlice>]"/ / such as preserveAspectRatio ="xMidYMid meet"
Copy the code

Defer is not important at this point, so we will ignore it for the moment and mainly understand the usage of align and meetOrSlice:

  • align: consists of two nouns representing the x and y alignment of the viewbox and viewport respectively.
value meaning
xMin Viewport and viewBox are aligned to the left
xMid The viewPort is aligned with the viewBox X-axis center
xMax Viewport and viewBox are aligned to the right
YMin Align the upper edge of the viewPort and viewBox. Notice that Y is capital.
YMid Align the viewPort with the center point of the viewBox’s Y-axis. Notice that Y is capital.
YMax Align the bottom edge of the viewPort and viewBox. Notice that Y is capital.
  • meetOrSlice: indicates how to maintain the ratio of height to width. There are three values meet, slice, and None.
    • meet– Default value, keep aspect ratio zoom viewBox to fit viewPort, may have residual blank.
    • slice– Keep aspect ratio and zoom in the direction of small proportion to fill the viewPort, the excess is clipped out.
    • none– Distort aspect ratio to fit viewPort adequately.
2.3.2, examples,

Example 1: preserveAspectRatio=”xMidYMid meet” indicates that the green box is aligned with the center point in the X and y directions of the monitor.

Example 2: preserveAspectRatio=”xMidYMin slice” indicates that the green box is aligned with the center point of the display in the X direction and the upper edge of the display in the Y direction.

Example 3: preserveAspectRatio=”xMidYMid Slice “indicates that the green box is aligned with the center point of the X and Y directions of the display, keeping the scale enlarged to fill the display beyond the part hidden;

Example 4: preserveAspectRatio=” None “; So that’s the unscaled answer.

What if applets do not support SVG tags

Wechat applet official does not support SVG tag, but decided to curve save the country, equivalent to implementing an SVG tag themselves: The Canvas renderer built in the small program is used to realize the subset of SVG standard in Cax and describe the behavior of SVG structure using JSX or HTM (Hyperscript Tagged Markup).

But today I want to talk about something else. As we know, although the applet does not support SVG tags, it supports background-image urls after SVG is transformed into base64, such as background-image: URL (“data:image/ SVG + XML…….). .

But I also have a requirement to change the color of each SVG path at any time, that is, the color is configurable:

To turn Base64 affirmation is more troublesome, have better way? A better way to implement SVG graphics is to use THE SVG XML format code directly, without base64 conversion.

3.1. URL encoding

To work directly with SVG XML format code, start by understanding the format of the Data URI. Highlight: Base64 is optional. If base64 is not specified, the following will use URL encoding.

Introduction to 3.1.1,

Percent-encoding, also known as URL encoding, is a context-specific encoding mechanism for uniform resource Locators (urls).

Principle: ASCII characters = % + two ASCII characters (hexadecimal). For example, if the ASCII code for character A is 0x61, the URL is encoded to get %61.

3.1.2 URL coding compression

Preface:

It is also possible to encode < Data > in the format of Data URIs entirely using URL encoding, such as encodeURIComponent(‘< SVG version=”1.1″ viewBox=… < / SVG > ‘). However, compared to the original SVG before escaping, the readability is much worse and the footprint is much larger. does not need to be fully encoded if you know more about URL encoding.

Body:

The RFC3986 document states that only unreserved and all reserved characters are allowed in a URL.

  • Reserved characters: Contains letters (A-ZA-Z), digits (0-9), and hyphens (_). For unreserved characters, percent-sign encoding is not required.
  • Reserved characters: characters with special meanings: /? @ # [](protocol, host, path, and other components that separate urls) and! * + $& '(),; =(Used as a separator in each component, such as the ampersand used to separate multiple key-value pairs in a query).
  • Restricted or unsafe characters: When placed directly in the Url, it may cause ambiguity in the parser, so this part needs percent encoding, e.g%,The blank space,Double quotation marks",Tip # < >And so on.

To sum up, you only need to encode restricted or unsafe characters.

  • JS processing is relatively simple, use replace to replace the character to be encoded, basically replace the following symbols is enough:
svgToUrl (svgData) { encoded = encoded .replace(/<! --(.*)-->/g,' 'Replace (/[\r\n]/g,' 'Replace (/).replace(/"/g, ' ') // Single quotes are reserved characters, Double quotation marks into a single quotes to reduce coding. The replace (/ % / g, '% 25'). The replace (/ & / g, '% 26). The replace (/ # / g, "% 23"). The replace (/ {/ g,' % 7 b). The replace (/} / g, '%7D') .replace(/</g, '%3C') .replace(/>/g, '%3E') return `data:image/svg+xml,${encoded}`}Copy the code
  • If used in CSS, SVG strings can be replaced with three apis from SASS version 3.3 and up.

    1. str_insert(string, insert, index)From:$string$indexInsert the character$insert;
    2. str_index(string, substring)Returns the$substring$stringThe first position in;
    3. str_slice(string, start_at, end_at = nil): Returns the slave character$stringIn the first$start_atStart to$end_atEnd a new string.

    Predecessors have been summed up, can go to https://github.com/leeenx/sass-svg/blob/master/sass-encodeuri.scss to view the complete code.

3.2. SVG compression

Generally, SVG is exported from Sketch, which has a lot of redundant code. If possible, SVGO is recommended to compress the original volume of SVG, such as clearing newlines and repeated Spaces. Delete document declaration; Delete comments; Delete desc description and so on.

Four,

The power of SVG is that it is unexpected, cool, and different.

Whether it is the wechat official account typography, foreignObject tag to achieve screenshots, achieve non-scale scaling, or background images directly using SVG XML format code, or path animation, stroke animation, graphic clipping, filter, etc., not mentioned above, can play new ways.

SVG an attribute can achieve an article, learning SVG can be said to challenge yourself, welcome to join the SVG learning queue.

· Recommended reading

Look at SVG Web dynamic effects

The mystery of URL encoding

CSS has a better form for inlining SVG images than Base64

Super powerful SVG SMIL Animation details

Teach you wechat public body page SVG interactive development

SVG introduction and screenshots and other applications


Welcome to the bump Lab blog: AOtu.io

Or pay attention to the bump Laboratory public account (AOTULabs), push the article from time to time: