preface

This is a pure SVG tutorial that removes the general knowledge of computer drawing, such as grid coordinates, path paths, fill strokes, etc., and can be supplemented or explained in more detail in Canvas Sitter tutorial (part 1) : Drawing.

What is the SVG

SVG stands for Scalable Vector Graphics

advantage

  • DOM interface implemented (more convenient than Canvas)
  • No need to install third-party extensions (such as Flash)
  • Can be read and modified by a wide variety of tools (such as notepad)
  • They are smaller and more compressible than JPEG and GIF images.
  • It’s scalable
  • Images can be printed with high quality at any resolution
  • Can be enlarged without degrading image quality
  • Text in the image is optional and searchable (great for mapping)
  • Can run with Java technology
  • It’s an open standard
  • The file is pure XML

SVG vs Canvas

  • There are different ways to describe graphics:

    • SVG is a language for describing 2D graphics using XML. Each graph that is drawn is treated as an object, and the browser can reproduce the graph automatically if the attributes of the SVG object change.
    • Canvas uses JavaScript to draw 2D graphics. Once the graph has been drawn, it does not continue to receive attention from the browser. If its position changes, the entire scene needs to be redrawn.
  • Whether controllable:

    • SVG is based on XML, which means it implements a DOM interface, every element is available, and you can attach JavaScript event handlers to an element.
    • Canvas is rendered pixel by pixel.
  • Applicable scenarios:

    • Canvas provides more primitive functions, suitable for pixel processing, dynamic rendering and large amount of data drawing

    • SVG is more sophisticated and suitable for static image display, high-fidelity document viewing and printing applications

Canvas SVG
Resolution dependent Resolution independent
Event handlers are not supported Support event handlers
Single Canvas element Multiple graphic elements (React, Path…)
Script only render Supports scripts and CSS
User interaction to pixel (x, Y) User interaction to graphic elements (PATH, RECT)
Ability to save the resulting image in.png or.jpg format High complexity slows down rendering (any application that overuses DOM is not fast)
Suitable for small area, large number of application scenarios (most suitable for graphic-intensive games) Suitable for large area, small number of application scenarios (such as Google Maps)

A simple example

<svg
  version="1.1"
  baseProfile="full"
  width="300"
  height="200"
  xmlns="http://www.w3.org/2000/svg"
>
  <rect width="100%" height="100%" fill="red" />

  <circle cx="150" cy="100" r="80" fill="green" />

  <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">
    SVG
  </text>
</svg>
Copy the code
  1. from<svg/>The root element starts:

    • Doctype declarations from (X)HTML should be discarded because SVG based DTD validation causes more problems than it solves.
    • Before SVG 2,versionProperties andbaseProfileProperty for other types of validation to identify versions of SVG. SVG 2 is not recommendedversionbaseProfileThese two properties.
    • As a dialect of XML, SVG must be properly bound to the namespace (in the XMLNS attribute).
    • widthheightProperty to set the width and height of this SVG document.
  2. : Draw a rectangle that completely covers the area of the image and set the background color to red.

  3. : A green circle with a radius of 80px is drawn in the center of the red rectangle (offset 150px to the right (cx) and 100px to the bottom (cy), i.e. the center is (cx,cy)).

  4. Draw text: Fill it with white and set the center anchor point (in this case, the center point corresponds to the middle point of the green circle)

The basic shape

This diagram shows all the basic shapes and the code to generate them:

<svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg">

  <rect x="10" y="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/>
  <rect x="60" y="10" rx="10" ry="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/>

  <circle cx="25" cy="75" r="20" stroke="red" fill="transparent" stroke-width="5"/>
  <ellipse cx="75" cy="75" rx="20" ry="5" stroke="red" fill="transparent" stroke-width="5"/>

  <line x1="10" x2="50" y1="110" y2="150" stroke="orange" fill="transparent" stroke-width="5"/>
  <polyline points="60 110 65 120 70 115 75 130 80 125 85 140 90 135 95 150 100 145"
      stroke="orange" fill="transparent" stroke-width="5"/>

  <polygon points="50 160 55 180 70 180 60 190 65 205 50 195 35 205 40 190 30 180 45 180"
      stroke="green" fill="transparent" stroke-width="5"/>

  <path d="M20, 230 Q40, 205 50230 T90, 230" fill="none" stroke="blue" stroke-width="5"/>
</svg>
Copy the code

The rectangle the rect

<! - rectangular - >
<rect x="10" y="10" width="30" height="30"/>
<! -- Rectangle with rounded corners -->
<rect x="60" y="10" rx="10" ry="10" width="30" height="30"/>
Copy the code
  • X /y: the x/y position in the upper left corner of the rectangle
  • Width/height: The width/height of the rectangle
  • Rx/ry: radius of the x/y direction of a rounded corner. The default value is 0

Circular circle

<circle cx="25" cy="75" r="20" />
Copy the code
  • R: radius of the circle
  • Cx/cy: the x/y position at the center of the circle

Ellipse of the ellipse

Ellipse is the more general form of the circle element, and you can scale the circle’s x and y radii respectively:

<ellipse  cx="75" cy="75" rx="20" ry="5"/>
Copy the code
  • Cx/cy: the x/y position at the center of the circle
  • Rx/ry: x/y radius of a circle

Line line

<line x1="10" x2="50" y1="110" y2="150"/>
Copy the code
  • x1 / y1: Starting position
  • x2 / y2: Finishing position

Line polyline

All points of a polyline are placed in a points property:

<polyline points="60 110, 65 120, 70 115, 75 130, 80 125, 85 140, 90 135, 95 150, 100 145"/>
Copy the code
  • Points: Each point must contain two numbers, one for the x coordinate and one for the y coordinate.

Make sure you make the fill color transparent, fill=”transparent”

Polygon polygon

Much like polylines, 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.

<polygon points="50 160, 55 180, 70 180, 60 190, 65 205, 50 195, 35 205, 40 190, 30 180, 45 180"/>
Copy the code

Path the path

The most common shape in SVG is also the most powerful, and it can create all shapes.

In addition, the path requires very few points to create smooth lines (such as 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.

<path d="M 20 230 Q 40 205, 50 230 T 90230"/>
Copy the code
  • D: a point set number column and other information about how to draw a path. The rule is “command + argument”.

    • M x y = moveto, move the stroke to(x,y)
    • L x y = lineto, will combine the current location with the new location(x,y)attachment
    • H x = horizontal lineto, move horizontally and connect
    • V y = vertical lineto, move and connect in the vertical direction
    • C x1 y1, x2 y2, x y = curveto, cubic Bezier curves
      • (x1,y1)Is the control point of the starting point
      • (x2,y2)Is the control point of the end point
      • (x,y)Is the end of the curve
    • S x2 y2, x y = smooth curveto, short for cubic Bezier curves
      • If it 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 used alone, that is, without a C or S command preceding it, the current point will be the first control point.
    • Quadratic Bezier curve Q x1 y1, x y = quadratic Bezier curveQuadratic Bezier curve
      • (x1,y1)Is the starting point
      • (x,y)Is the end of the curve
    • T x y = smooth quadratic Bézier curvetoQuadratic Bezier curve for short
      • If followed by a Q or T command, it will infer a new control point through the previous control point
      • If used alone, the control point is thought to be the same point as the end point, that is, a straight line.
    • A = elliptical Arc, arc, see below for details
    • Z = closepath, close the path and draw a line from the current point to the start of the path, case insensitive

Each command can be represented in two ways,

  • Uppercase letters indicate absolute location.
  • Lowercase letters to indicate relative positioning (for example, move 10px up and 7px left from the previous point).

You can also learn more about the path path by using the Path path in the Canvas.

arc

A rx ry x-axis-rotation large-arc-flag sweep-flag x y
Copy the code
  • rx / ry: x/y radius
  • x-axis-rotation: Rotation, the positive number is clockwise
  • large-arc-flag: The size of the Angle, divided by 180 degrees,
    • 0 is the small Angle arc,
    • 1 is the big Angle arc.
  • sweep-flag: Arc direction
    • Zero means counterclockwise
    • 1 indicates clockwise
  • x / y: the end of the arc

Large-arc-flag and sweep-flag can be understood in combination with examples:

<! -- Small Angle arc & Counterclockwise -->
<path
  d="M80 80 A 45 45, 0, 0, 0, 125 125 L 125 80 Z"
  fill="green"
/>
<! -- Large Angle arc & Counterclockwise -->
<path
  d="M230 80 A 45 45, 0, 1, 0, 275 125 L 275 80 Z"
  fill="red"
/>
<! -- Small Angle arc & clockwise -->
<path
  d="M80 230 A 45 45, 0, 0, 1, 125 275 L 125 230 Z"
  fill="purple"
/>
<! -- Large Angle arc & clockwise -->
<path
  d="M230 230 A 45 45, 0, 1, 1, 275 275 L 275 230 Z"
  fill="blue"
/>
Copy the code

Fill and Stroke

The opacity

Fill-opacity and stroke-opacity control the opacity of the fill and stroke.

Of course, you can also specify transparency using RGBA.

stroke

Just like the lines in the Canvas, SVG also has stroke-width, stroke-linecap, stroke-linejoin, stroke-miterLimit, stroke-Dasharray, and stroke-dashoffset.

Using CSS

We can use CSS to define styles, but you need to change background-color and border to fill and stroke.

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.

Inline styles like this:

<rect x="10" height="180" y="10" width="180" style="stroke: black; fill: red;"/>
Copy the code

Or by putting styles in a

element, you can reuse the same set of styles:

<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

The gradient

The implementation logic of gradient is very similar to canvas, but SVG is implemented as a node:

    <svg width="400" height="500" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="Gradient1" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stop-color="red" />
          <stop offset="50%" stop-color="black" stop-opacity="0" />
          <stop offset="100%" stop-color="blue" />
        </linearGradient>
        <radialGradient
          id="RadialGradient1"
          cx="0.5"
          cy="0.5"
          r="0.5"
          fx="0.25"
          fy="0.25"
        >
          <stop offset="0%" stop-color="red" />
          <stop offset="100%" stop-color="blue" />
        </radialGradient>
      </defs>
      <rect
        x="10"
        y="10"
        rx="15"
        ry="15"
        width="100"
        height="100"
        fill="url(#RadialGradient1)"
      />
      <rect
        x="120"
        y="10"
        rx="15"
        ry="15"
        width="100"
        height="100"
        fill="url(#Gradient1)"
      />
    </svg>
Copy the code

The linearGradient defaults to horizontal, and you can change the gradient direction by setting the starting point (x1,y1) and ending point (x2,y2).

RadialGradient’s rules are a little more complicated,

  • center(cx,cy)And radiusr, describes the position of the gradient edge
  • The focus of(fx,fy), describes the center of the gradient

The

node says what color should be at a particular position in the gradient by specifying the offset and stop-color properties at the position

Gradient spreadMethod

  • padWhen the gradient reaches the end, the final offset color is used to fill the remaining space of the object
  • reflectThe gradient effect is repeated in a reverse-back fashion, that is, starting with the color at 100% offset, gradually moving to 0%, and then back to 100% offset.
  • repeat, andreflectThe difference is to jump back to the original color and continue the gradient.

pattern

Like gradients, needs to be placed inside

of an SVG document.

You can include any other basic shape inside the Pattern element, such as drawing two rectangles and a circle:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <defs>
    <linearGradient id="Gradient1">
      <stop offset="5%" stop-color="white"/>
      <stop offset="95%" stop-color="blue"/>
    </linearGradient>
    <linearGradient id="Gradient2" x1="0" x2="0" y1="0" y2="1">
      <stop offset="5%" stop-color="red"/>
      <stop offset="95%" stop-color="orange"/>
    </linearGradient>

    <pattern id="Pattern" x="0" y="0" width="25" height="25">
      <rect x="0" y="0" width="50" height="50" fill="skyblue"/>
      <rect x="0" y="0" width="25" height="25" fill="url(#Gradient2)"/>
      <circle cx="25" cy="25" r="20" fill="url(#Gradient1)" fill-opacity="0.5"/>
    </pattern>

  </defs>

  <rect fill="url(#Pattern)" stroke="black" x="0" y="0" width="200" height="200"/>
</svg>
Copy the code

The text

<text>

The

element is used to define text.

<text x="10" y="10" text-anchor="start">Hello World!</text>
Copy the code
  • x/y: determines where text is displayed in the viewport
  • text-anchor: Indicates the horizontal alignment position of the textstart,middle,endinherit
  • rotate: Rotate all characters by an Angle. If it is a sequence, rotate each character individually to that value, and rotate the remaining characters to the last value.

Each of the following attributes can be set as an SVG attribute or as a CSS declaration: Font-family, font-style, font-weight, font-variant, font-stretch, font-size, font-size-adjust, Kerning, letter-spacing, word-spac Ing and text – decoration.

<tspan>

Marks a child of a large block of text, which must be a child of a Text element or other TSPAN element.

<text x="10" y="20">
  Hello SVG! this is
  <tspan font-weight="bold">bold</tspan>
  and
  <tspan fill="red">red</tspan>
  .
</text>
Copy the code

<textPath>

Place text according to the shape of the element. Use the xlink:href attribute to get an arbitrary path, align the characters to the path, and then the character will go around the path and follow it:

<defs>
  <path
    id="MyPath"
    d="M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100"
  />
</defs>
<text font-family="Verdana" font-size="42.5">
  <textPath xlink:href="#MyPath">
    We go up, then we go down, then up again
  </textPath>
</text>
Copy the code

Transform basic Transform

The transform property is a collection of transformation rules that can be concatenated, separated by Spaces.

<g>

The transformation added to the element G is applied to all of its children. In fact, that’s its sole purpose.

<g fill="red">
  <rect x="0" y="0" width="10" height="10" />
  <rect x="20" y="0" width="10" height="10" />
</g>
Copy the code

Output two red rectangles.

translation

translate(<x> [<y>])
Copy the code

Move elements by x and y vectors, default to 0 if the y vector is not provided

<rect x="0" y="0" width="10" height="10" transform="Translate (30, 40)" />
Copy the code

The rectangle will move to the point 30,40.

rotating

rotate(<a> [<x> <y>])
Copy the code

To perform a rotation transformation on a specified point at a given Angle. If x and y are not provided, the current element coordinate origin is default. Otherwise, we rotate at the origin of (x,y).

<rect x="20" y="20" width="20" height="20" transform="rotate(45)" />
Copy the code

A square, rotated 45 degrees.

The zoom

scale(<x> [<y>])
Copy the code

Specify a scaling operation with x and y. If y is not provided, assume that it is equivalent to x.

<! -- uniform scale -->
<circle cx="0" cy="0" r="10" fill="red" transform="scale(4)" />

<! -- vertical scale -->
<circle cx="0" cy="0" r="10" fill="yellow" transform="The scale (1, 4)" />

<! -- horizontal scale -->
<circle cx="0" cy="0" r="10" fill="pink" transform="Scale (4, 1)" />
Copy the code

oblique

Specifies the tilt transformation of the tilt a° along the X-axis.

skewX(<a>)
Copy the code

Specifies the inclination transformation of inclination a° along the Y-axis.

skewY(<a>)
Copy the code

Use a rectangle to make an oblique diamond.

<rect x="- 3" y="- 3" width="6" height="6" fill="red" transform="skewX(30)" />
Copy the code

Cut and mask

Clipping removes part of the content of an element defined elsewhere, which can only be displayed or not (no translucency effect).

Masks allow soft edges calculated using opacity and gray value masks.

tailoring

Define a clipping path (as visible range, style invalid) with

as the clip-path attribute value of the element that needs to be clipped. If the graph is outside the area bounded by the current clipping path, the excess part will not be drawn.

For example, we crop a semicircle:

<defs>
  <clipPath id="cut-off-bottom">
    <rect x="0" y="0" width="200" height="100" />
  </clipPath>
</defs>

<circle cx="100" cy="100" r="100" clip-path="url(#cut-off-bottom)" />
Copy the code

mask

The

element is used to define such a mask element. The transparent mask layer can be any other graphic object or a

element.

For example, using masks to fade out elements:

<svg
  version="1.1"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
>
  <defs>
    <linearGradient id="Gradient">
      <stop offset="0" stop-color="white" stop-opacity="0" />
      <stop offset="1" stop-color="white" stop-opacity="1" />
    </linearGradient>
    <mask id="Mask">
      <rect x="0" y="0" width="200" height="200" fill="url(#Gradient)" />
    </mask>
  </defs>

  <rect x="0" y="0" width="200" height="200" fill="red" mask="url(#Mask)" />
</svg>
Copy the code

HTML 5 series

  • To understand it
  • Enhanced forms
  • Audio and Video
  • Canvas nanny tutorial (part 1) : Drawing
  • Canvas Nanny tutorial (part 2) : Animation
  • Finally drawing in SVG
  • Geolocation
  • A drag-and-drop operation
  • Understand the Web Worker
  • Understand the Web Storage
  • Understand the WebSocket