The purpose of this article is to explain how to achieve data large screen step by step.

What is SVG?

  • SVG stands for Scalable Vector Graphics
  • SVG is used to define vector-based graphics for networking
  • SVG uses XML format to define graphics
  • SVG images do not lose graphical quality when they are enlarged or resized
  • SVG is the World Wide Web Consortium standard
  • SVG is integrated with W3C standards such as DOM and XSL

History and advantages of SVG

In January 2003, SVG 1.1 was established as a W3C standard.

The organizations involved in defining SVG are sun Microsystems, Adobe, Apple, IBM, and Kodak.

The advantages of using SVG over other image formats are:

  • SVG can be read and modified by a wide variety of tools (such as Notepad)
  • SVG is smaller and more compressible than JPEG and GIF images.
  • SVG is scalable
  • SVG images can be printed with high quality at any resolution
  • SVG can be enlarged without degrading image quality
  • Text in SVG images is optional and searchable (great for making maps)
  • SVG can work with Java technology
  • SVG is an open standard
  • SVG files are pure XML

A simple example

<svg width="200" height="200" viewbox="0 0 100 100"></svg>
Copy the code
  • Width: the width of the
  • Height: height

viewBox

It says on the MDN

The viewBox property allows you to specify a given set of graphics stretches to fit a particular container element. The value of the viewBox property is a list of four arguments min-x, min-y, width and height, separated by Spaces or commas, specifying a rectangular region in user space mapped to the given element. See the property preserveAspectRatio. Negative width and height values are disallowed, and 0 disables element rendering.

I didn’t understand this at first

Let’s take a look at the graph below

The first two parameters represent x,y, the coordinates of the top left corner of the canvas. The last two parameters represent width,height, and canvas size.

Nested coordinate system

Another SVG element can be inserted into the document to create a new viewport and coordinate system, which means that another SVG can be nested within SVG, each with its own separate viewport and coordinate system.

The basic shape

Line segment

The line element specifies the starting and ending coordinates of a line segment using the x1,y1,x2,y2 attributes. Has the following features:

features instructions
stroke-width Stroke width. The grid line is located in the middle of the stroke. You can use THE SHApe-rendering value of CSS to control the anti-aliasing characteristics
stroke Stroke color
stroke-opacity The opacity of the line
stroke-dasharray Dashed lines, consisting of a series of even numbers (which are automatically repeated to be even), indicate line length – gap – line length – gap…

Demo

rectangular

Rect element, using x,y,width,height to represent a rectangle

features instructions
fill Fill color
fill-opacity Fill opacity
stroke Border color
stroke-width The width of the border, the border is riding on the edge of the rectangle, half outside the rectangle, half inside the rectangle
rx/ry Rounded rectangle with a maximum of half the width/height of the rectangle. If only one is specified, both are considered to be the same value

Demo

Circular and elliptical

Circle elements represent circles defined by cx,cy,r attributes and ellipse elements represent ellipses defined by cx,cy,rx,ry

features instructions
fill Fill color
fill-opacity Fill opacity
stroke Border color
stroke-width Border width, the border is riding on the edge of the circle, half outside the circle/oval and half inside the circle/oval

Demo

The path

The path command

All basic shapes in SVG are short for PATH, but the short form is recommended because it makes SVG documents more readable.

The path element is more general and can be used to draw an arbitrary shape by drawing a series of interconnected lines, arcs, and curves. These Outlines can also fill in or draw contour lines, and can be used to define clipping areas or masks.

The following table summarizes the path commands, where upper case indicates absolute coordinates and lower case indicates relative coordinates:

The command parameter instructions
M m x y Move the brush to the specified coordinates
L l x y Draws a line to a given coordinate
H h x Draws a horizontal line to the given x coordinate
V v y Draw a vertical line to the given y coordinate
A a rx ry x-axis-rotation large-arc sweep x y The arc curve command has seven parameters, including x radius, Y radius, rotation Angle, great circle identifier, clockwise identifier, target point X, and target point Y. Large circles and counterclockwise are represented by 0 and 1. 0 represents a small circle and counterclockwise
Q q x1 y1 x y Draw a quadratic Bezier curve from the current point to x,y control points x1,y1
T t x y Draw a smooth quadratic Bezier curve from the current point to x,y. The control point is the central symmetric point of the control point of the previous Q command. If there is no previous command, the current point is the control point.
C c x1 y1 x2 y2 x y Draw a cubic Bezier curve from the current point to control points x,y of x1,y1, x2,y2
S s x2 y2 x y Draws a smooth cubic Bezier curve from the current point to x,y. The first control point is the central symmetry point of the second control point of the previous C command. If there is no previous curve, the first control point is the current point.

The filling rule of the path can also be specified by using the fill-rule attribute. If a hollow shape needs to be filled, it is only necessary to pay attention to the clockwise direction of the outer path and the clockwise direction of the inner hollow area.

Bessel curve

Bezier curve is a mathematically described curve widely used in computer graphics and animation. In vector diagrams, Bezier curve is used to define a smooth curve that can be amplified indefinitely.

The formula

The linear equation

Given points P0, P1, the linear Bates curve is just a straight line between two points. The line is given by the following formula:

And this is equivalent to linear interpolation.

Quadratic formula

The path of the quadratic Bates curve is traced by B (t) of the given points P0, P1, and P2:

Cubic formula

The points P0, P1, P2, and P3 define the cubic Bates curve in the plane or in three dimensions. It starts at P0 going to P1, and it goes from P2 to P3. It usually doesn’t go through P1 or P2; These two points are just there to provide directional information. The distance between P0 and P1 determines “how long” the curve moves toward P2 before turning toward P3. The parameter form of the curve is:

Modern imaging systems, such as PostScript, parabolic and Metafont, use cubic Bates curves consisting of Bates splines to delineate curves.

General parameter formula

The Bates curve of order n can be inferred as follows. Give points P0, P1… , Pn, and its Bates curve is:

The above formula can be expressed recursively as follows: by denotes the points P0, P1… And the Bates curve determined by Pn. In ordinary terms, order Bates curves, namely the interpolation between two order Bates curves.

formula

  1. A curve that begins at P0 and ends at Pn is known as an endpoint interpolation property.
  2. The necessary and sufficient condition for a curve to be a straight line is that all control points lie on the curve. Similarly, a Bessel curve is a straight line only if the control points are collinear.
  3. The beginning (end) of a curve is tangent to the first (last) segment of a Bessel polygon.
  4. A curve can be cut into two or more sliver curves at any point, and each sliver curve is still a Bezier curve.
  5. Some seemingly simple curve (such as a circle) cannot be described with bezier accurate, or segmented into Bessel curve (although when each internal locus of control on the unit circle of the external locus of control on the horizontal or vertical distance too, bezier curve is divided into four sections, can be less than one over one thousand of the approximation of the maximum error of the radius in the circle).
  6. Curves at a fixed offset (from a given Bezier curve), also known as offset curves (pseudoparallel to the original curve, such as the offset between two railroad tracks) cannot be accurately formed as Bates curves (except for some trivial instances). However, existing heuristics can often give approximations for practical use.

See above formula confused, how to do?

Don’t worry, we ignore it, continue to read……

Bezier curve drawing

There are many types of Bezier curves, but in the path element, there are only two kinds of Bezier curves: cubic bezier curves and quadratic Bezier curves.

Let’s start with the slightly more complex cubic Bezier curve C. The cubic Bezier curve needs to define a point and two control points, so using the C command to create the cubic Bezier curve, we need to set three sets of coordinate parameters:

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

The last coordinate here (x,y) represents the end of the curve, the other two coordinates are the control points, (x1,y1) is the control point of the starting point, and (x2,y2) is the control point of the end point. If you’re familiar with algebra or calculus, you’ll understand control points, control points describe the slope of the starting point of a curve, the slope of each point on the curve, the gradient from the starting slope to the ending slope.

< SVG width = "190 px" height = "160 px" version = "1.1" XMLNS = "http://www.w3.org/2000/svg" > < path d = "M10 10 C 20 20, 40, 20 50 10" stroke="black" fill="transparent"/> <path d="M70 10 C 70 20, 120 20, 120 10" stroke="black" fill="transparent"/> <path d="M130 10 C 120 20, 180 20, 170 10" stroke="black" fill="transparent"/> <path d="M10 60 C 20 80, 40 80, 50 60" stroke="black" fill="transparent"/> <path d="M70 60 C 70 80, 110 80, 110 60" stroke="black" fill="transparent"/> <path d="M130 60 C 120 80, 180 80, 170 60" stroke="black" fill="transparent"/> <path d="M10 110 C 20 140, 40 140, 50 110" stroke="black" fill="transparent"/> <path d="M70 110 C 70 140, 110 140, 110 110" stroke="black" fill="transparent"/> <path d="M130 110 C 120 140, 180 140, 170 110" stroke="black" fill="transparent"/> </svg>Copy the code

In the example above, we created nine cubic Bezier curves.

You can concatenate several Bezier curves to create a long, smooth curve. Normally, the control points on one side of a point are the symmetry of the control points on the other side (to keep the slope constant). In this way, you can use a shorthand bezier curve command S, as follows:

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

The S command can be used to create the same Bezier curve as before, but if the S command follows a C or S command, its first control point is assumed to be the central symmetry point of the second control point of 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. The following is an example of the syntax of the S command. In the figure, the control points marked red on the left are marked blue.

< SVG width = "190 px" height = "160 px" version = "1.1" XMLNS = "http://www.w3.org/2000/svg" > < path d = "M10 40 10 80 C, 65 10, 95 80 S 150 150, 180 80" stroke="black" fill="transparent"/> </svg>Copy the code

Another type of Bezier curve available is the quadratic Bezier curve Q, which is simpler than the cubic Bezier curve and requires only one control point, which is used to determine the slope of the curve at the beginning and end. So it requires two sets of parameters, control points and endpoint coordinates.

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

< SVG width = "190 px" height = "160 px" version = "1.1" XMLNS = "http://www.w3.org/2000/svg" > < path d = "M10 80 Q 95 10, 180, 80" stroke="black" fill="transparent"/> </svg>Copy the code

Just as the cubic Bezier curve has an S command, the quadratic Bezier curve has an almost identical T command, which extends the quadratic Bezier curve with shorter parameters.

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

As before, the shortcut command T will infer a new control point from the previous control point. This means that after your first control point, you can create a fairly complex curve by just defining the end 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.

< SVG width = "190 px" height = "160 px" version = "1.1" XMLNS = "http://www.w3.org/2000/svg" > < path d = "M10 80 Q 10, 52.5 95 80 T 180 80" stroke="black" fill="transparent"/> </svg>Copy the code

Although cubic Bezier curves have greater degrees of freedom, the results achieved by both curves are almost the same. Which curve to use usually depends on the requirements and how much you rely on the symmetry of the curve.

Demo

Here are two sites where you can try to plot your own Bezier curve:

Bezier curve editor high order Bezier curve editor bezier curve mini-game

The gradient

Fill shapes or strokes with patterns and gradients in addition to solid colors like Fill and stroke.

Linear gradient

A linear gradient is a series of colors transitioning along a straight line, specifying the desired color at a specific location, known as a gradient point. Gradient points are part of the gradient structure, and color is part of the presentation.

Linear gradients are expressed using the linearGradient element:

<defs> <linearGradient id="linear"> <stop offset="0%" style="stop-color:#ffcc00;" ></stop> <stop offset="100%" style="stop-color:#0099cc;" ></stop> </linearGradient> </defs> <rect x="20" y="20" width="200" height="100" style="fill:url(#linear); stroke:black;" ></rect>Copy the code

The stop element has two required attributes: offset and stop-color. The offset attribute is used to specify at which point the color should equal stop-color. The value of offset ranges from 0% to 100%.

Attributes of the stop element:

attribute instructions
offset Mandatory. The value ranges from 0% to 100%
stop-color Required, corresponding to the color of the offset position
stop-opacity The opacity of the corresponding offset position

LinearGradient element attributes:

attribute instructions
x1,y1 The starting position of the gradient, expressed as a percentage, is left to right by default
x2,y2 The end point of the gradient is expressed as a percentage
spreadMethod How to fill the offset if it does not cover the entire object. Pad: The starting or ending color extends to the edge of the object. Repeat: The process from the beginning to the end. Reflect: The gradient repeats in an end – start – end order.

Demo

SVG animation

CSS animations

Modern browsers all support CSS carded SVG animation, using CSS to process SVG animation requires two steps: first, select the element to move, and then set the animation properties as a whole. The second is to tell the browser which attribute of the selected element to change and at what stage of the animation. This is all defined in the @keyframes specifier.

Let’s implement a dynamically changing circle:

const x = 100; const y = 100; const radius = 20; Const outerRadius = radius * 2.2; const color = '#5ac1dc'; return ( <svg width="200" height="200" viewBox="0 0 200 200"> <defs> <style>{` .gs-service-dot-inner{animation:scaleDot 2s infinite; Gs - service - dot - outer {}. Opacity: 0.27; animation:scaleDot 2s infinite; } @keyframes scaleDot { 0%{transform: scale(1); 50%} {the transform: scale (1.3); } 100%{transform: scale(1); } }`}</style> </defs> <circle key="inner" className="gs-service-dot-inner" cx={x} cy={y} r={radius} fill={color} style={{ transformOrigin: `${x}px ${y}px` }} /> <circle key="outer" className="gs-service-dot-outer" cx={x} cy={y} r={outerRadius} fill={color} style={{ transformOrigin: `${x}px ${y}px` }} /> </svg> );Copy the code

Demo

How do you draw a curve that moves

We need to use two properties

  • Stroke-dasharray controls the dotted pattern pattern used for stroke. This property allows you to specify the length of each segment drawn. The second value is the length of the space between segments.
  • The stroke-Dashoffset property specifies the distance from the dash mode to the start of the path. This property lets you specify the starting offset for each segment.
<path stroke="#000" stroke-width="4.3" fill="none" d="..." Stroke - dasharray = 988.00 "988.00" stroke - dashoffset = "988.00" / >Copy the code

Set both attributes to the maximum value (the total length of the line) and then slowly reduce the dashoffset attribute. Wow, the lines are drawn dynamically!

You can get the length of the line from DOM:

var path = document.querySelector('.squiggle-container path');
path.getTotalLength();
Copy the code

You can then use CSS animation to reduce the dashoffset property value and draw the line dynamically.

Demo

Try dragging to modify the two properties yourself

Moving along the path

If you need to move a transition object along a complex path, use the animateMotion element.

<circle cx="0" cy="0" r={2} Fill ="#FF4AA1"> <animateMotion path="M20,20 C20,104 216,300 300,300" dur="2s" repeatCount="indefinite" rotate="auto"></animateMotion> </circle>Copy the code

In the preceding example, you can rotate a circle along path=”M20,20 C20,104 216,300 300,300″. During the movement, you need to set the rotate attribute of the animateMotion element to auto.

If you already have a path trace and don’t want to define path again in the animateMotion element, you can use the mPath element. The mPath element is defined inside the animateMotion element, using the path specified by the href reference.

<path id="gsPath" class="gs-edge-path" d="M20,20 C20,104 216,300 300,300"></path>
<circle cx="0" cy="0" r="2" fill="#FF4AA1">
	<animateMotion dur="2s" repeatCount="indefinite" rotate="auto">
		<mpath href="#gsPath"></mpath>
	</animateMotion>
</circle>
Copy the code

Demo

Draw the pie chart

Figure out the coordinates of some point on the circle

To draw a graph, we first calculate the coordinates of the points on the circle.

Let’s take an Angle of 70 degrees as an example to draw a sector area from the center of the circle to the vertex (the vertex coordinates are the center of the circle x, the center of the circle y-radius R), then to another point at the Angle of 70 degrees, and then back to the center of the circle to draw a sector.

So the problem is to figure out the coordinates of the other point. From the formula above, x1 is the center of the circle x plus the radius r times cosine of 90 minus 70. Y1 is the center of the circle y minus the radius r times sine of 90 minus 70.

We can do this using the JavaScript built-in functions math. sin and math.cos. But it’s important to note that math. sin and math. cosine take radians, not angles, so we’re going to do a conversion

Radians = (2 * math.pi / 360) * AngleCopy the code

We can calculate the coordinates by the following formula: X1 is the center coordinate x + radius r * cos((2 * math.pi / 360) * (90-70)) y1 is the center coordinate y – radius r * sin((2 * math.pi / 360) * (90-70))

The < path d = "M249.89, a89.3 l0 272.5-89.3, 89.3, 0,0,1,83.9, 58.7 Z" > < / path >Copy the code

In the same way, we can draw arcs

< path d = "M249.89, a89.3 183.2, 89.3, 0,0,1,83.9, 58.7 L373.4 A131.43 227.5, 131.43, 0,0,0,249.89, 141.07 Z" > < / path >Copy the code

The text

The text element takes the specified X and Y values as the baseline position of the first character of the element’s content. The default style is black filled with no outline.

attribute instructions
font-family A series of font names separated by Spaces or generic font names
font-size If there are multiple lines of text, font-size is the distance between two parallel baselines
font-weight Two values: bold(bold) and nromal(default)
font-style Two common values :italic(italic) and normal
text-decoration Possible values: None,underline,overline,line-through
word-spacing The distance between words
letter-spacing The spacing between letters
text-anchor Alignment: start,middle,end
textLength Sets the length of the text
lengthAdjust When you specify textLength, you can use the lengthAdjust attribute to set how characters are adjusted, and only the spacing of characters is adjusted when spacing is set to spacing(the default). When the value is spacingAndGlyphs, adjust both the character spacing and the character size itself

If you want to arrange text along a path, you need to use the textPath element. You need to place text inside a textPath element, and then reference a defined Path element using the href attribute of the textPath element.

< defs > < path id = "ch_title_path_0" d = "M249.89, a110.365 162.135, 110.365, 0,0,1,103.7, 72.6" > < / path > < / defs > < text fill="#ffffff" font-size="20"> <textPath href="#ch_title_path_0" startOffset="50%" text-anchor="middle" Domination-baseline ="central"> </textPath> </text>Copy the code

Set up thestartOffset="50%",text-anchor="middle"Center the text horizontally

Set up thedominant-baseline="central"Center the text vertically

The rotate transformation

Rotate the coordinate system according to the specified Angle. By default, in the coordinate system, the Angle measurement increases clockwise.

Note that rotation is centered on the origin unless otherwise specified. Rotate (Angle) rotate(-centerx, -centery) Rotate (Angle) rotate(-centerx, -centery)

But there’s an easier way: Rotate (Angle,centerX,centerY)

So now we have one piece of the pie

And then we just have to do the same for the other pieces, rotate them

Add a few more pieces to form a complete pie chart

Demo

How to draw a moving line D3js SVG Basics