1. Overview

SVG, short for Scalable Vector Graphics, is an image format based on XML syntax. Other image formats are based on pixel processing, while SVG makes a shape description for the image, so essentially it is a text file with small size, and will not be distorted no matter how many times it is enlarged.

SVG files can be inserted into a web page directly, becoming part of DOM, and then manipulated with JavaScript and CSS.

<!DOCTYPE html> <html> <head></head> <body> <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> </body> </html>

The above is a code example for SVG being inserted into a web page directly.

SVG code can also be written in a separate file and then inserted into the web page using tags such as <img> , <object> , <embed> , <iframe> .

<img src="circle.svg"> <object id="object" data="circle.svg" type="image/svg+xml"></object> <embed id="embed" src="icon.svg" type="image/svg+xml"> <iframe id="iframe" src="icon.svg"></iframe>

SVG files also can be used in CSS.

.logo { background: url(icon.svg); }

SVG files can be converted to BASE64 encoding and then written to the web page as a Data URI.

<img src="data:image/svg+xml;base64,[data]">

2. Syntax

2.1 <svg>

The SVG code should be placed in the top-level tag <svg>. Here is an example.

<svg width="100%" height="100%"> <circle id="mycircle" cx="50" cy="50" r="50" /> </svg>

The width and height properties of <svg> specify the width and height of the SVG image in the HTML element. In addition to the relative units, absolute units (in pixels) can also be used. If you don't specify these two properties, the default size of the SVG image will be 300 pixels (width) x 150 pixels (height).

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

<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> property contains four numbers: the horizontal and vertical coordinates of the upper left corner, and the width and height of the viewport. In the above code, the SVG image is 100 pixels x 100 pixels, and the viewBox property specifies that the viewport starts at (50, 50). So what you actually see is a quarter circle at the lower right corner.

Note that the viewport must be adaptive to the space where it is. 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 be four times to fit the size of the SVG image.

If you don't specify the properties of the width and height , specifying only the viewBox property is equivalent to giving only the aspect ratio of the SVG image. Thus the default size of the SVG image will be equal to the size of the HTML element in it.

2.2 <circle>

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 above code defines three circles. The cx , cy , and r properties of the <circle> tag are used to specify the abscissa, ordinate, and radius respectively, which are in the unit of pixels. The coordinates are all relative to the origin at the upper left corner of the <svg> canvas.

The class property is used to specify the corresponding CSS class.

.red { fill: red; } .fancy { fill: none; stroke: black; stroke-width: 3pt; }

The CSS properties in SVG are different from the HTML elements.

fill: fill color

stroke: stroke the color

stroke-width: the width of the border

2.3 <line>

The <line> tag is used to draw a straight line.

<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 properties of x1 and y1 for the <line> tag indicate the abscissa and ordinate of the starting point of the line segment respectively; the properties of x2 and y2 represent the abscissa and ordinate of the end point of the line segment respectively; and the style property indicates the style of the line segment.

2.4 <polyline>

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 property of the <polyline> specifies the coordinates of each endpoint; a comma is used to separate the abscissa and ordinate, and a space is used to separate the points.

2.5 <rect>

The <rect> tag is used to draw a rectangle.

<svg width="300" height="180"> <rect x="0" y="0" height="100" width="200" style="stroke: #70d5dd; fill: #dd524b" /> </svg>

The x and y properties of <rect> specify the abscissa and ordinate for the endpoint of the upper left corner of the rectangle; and the properties of the width and height specify the width and height of the rectangle (in pixels).

2.6 <ellipse>

The <ellipse> tag is used to draw an ellipse.

<svg width="300" height="180"> <ellipse cx="60" cy="60" ry="40" rx="20" stroke="black" stroke-width="5" fill="silver"/> </svg>

The cx and cy properties of <ellipse> specify the abscissa and ordinate of the ellipse center (in pixels); and the rx and ry properties specify the radius (in pixels) of the elliptical horizontal and vertical axes.

2.7 <polygon>

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 property of the <polygon> specifies the coordinates of each endpoint; a comma is used to separate the abscissa and ordinate, and a space is used to separate the points.

2.8 <path>

The <path> tag is used to make 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 property of the <path> represents the drawing order, the value of which is a long string, and each letter of the string represents a drawing action which is followed by coordinates.

M：move to

L：line to

Z：close the path

2.9 <text>

The <text> tag is used to draw text.

<svg width="300" height="180"> <text x="50" y="25">Hello World</text> </svg>

The x and y properties of <text> represent the abscissa and ordinate of the starting point in the text block baseline. The style of the text can be specified with the properties of class or style .

2.10 <use>

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 property of <use> specifies the node to be copied, and the x and y are the coordinates of the upper left corner for <use> . In addition, you can also specify the width and height values.

2.11 <g>

The <g> tag is used to gather 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>

2.12 <defs>

The <defs> tag is used for custom shapes, the internal code of which won't be displayed, and it's for reference only.

<svg width="300" height="100"> <defs> <g id="myCircle"> <text x="25" y="20">圆形</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>

2.13 <pattern>

The <pattern> tag is used to customize a shape which can be referenced to fill 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 the dots mode. patternUnits="userSpaceOnUse" indicates that the width and length of the <pattern> are actual pixel values. Then, the dots mode is specified to fill the rectangle.

2.14 <image>

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, the xlink:href property of the <image> indicates the source of the image.

2.15 <animate>

The <animate> tag is used to create 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 move continuously in order to generate an animation.

The properties of the <animate> are as follows.

attributeName: The property name of the animation.

from: The initial value of a single animation.

to: The end value of a single animation.

dur: The duration of a single animation.

repeatCount: The loop mode of the animation.

You can define animations with multiple properties.

<animate attributeName="x" from="0" to="500" dur="2s" repeatCount="indefinite" /> <animate attributeName="width" to="500" dur="2s" repeatCount="indefinite" />

2.16 <animateTransform>

The <animate> tag can't work on the transform property of CSS, so if you need to morph, you should use the <animateTransform> tag.

<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 the <animateTransform> is to rotate . There are three numbers in the values of the from and to : The first number is the angle value, and the second and the third 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 it should rotate around the (400, 400) for 360 degrees before the rotation ends.

3. JavaScript operation

3.1 DOM operation

If the SVG code is written into an HTML page directly, it will become part of the DOM and can be manipulated directly with 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>

Once the code above is inserted into the page, you can customize the style with CSS.

circle { stroke-width: 5; stroke: #f00; fill: #ff0; } circle:hover { stroke: #090; fill: #fff; }

Then you can manipulate the SVG in the 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 you click on the graphic, the r property of the circle element will be changed.

3.2 Obtain SVG DOM

We can obtain the SVG DOM by using the <object> , <iframe> , <embed> tags to insert an SVG file.

var svgObject = document.getElementById('object').contentDocument; var svgIframe = document.getElementById('iframe').contentDocument; var svgEmbed = document.getElementById('embed').getSVGDocument();

Note that if you insert an SVG file using the <img> tag, you won't be able to get the SVG DOM.

3.3 Read SVG source code

Since the SVG file is a piece of XML text, you can read the SVG source by the way of 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>

You can use the serializeToString() method of the XMLSerializer instance to get the code for the SVG element.

var svgString = new XMLSerializer() .serializeToString(document.querySelector('svg'));

3.4 Convert SVG images to Canvas images

First, you need to create a new Image object and assign the SVG image to the src property 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;

Once 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); };

4. Example: line chart

Let's draw a data table into a line chart.

Date |Amount -----|------ 2014-01-01 | $10 2014-02-01 | $20 2014-03-01 | $40 2014-04-01 | $80

The above graph will be drawn as a coordinate system, with Date as the horizontal axis and Amount as the vertical axis, and each line of the data drawn as one data point.

<svg width="350" height="160"> <g class="layer" transform="translate(60,10)"> <circle r="5" cx="0" cy="105" /> <circle r="5" cx="90" cy="90" /> <circle r="5" cx="180" cy="60" /> <circle r="5" cx="270" cy="0" /> <g class="y axis"> <line x1="0" y1="0" x2="0" y2="120" /> <text x="-40" y="105" dy="5">$10</text> <text x="-40" y="0" dy="5">$80</text> </g> <g class="x axis" transform="translate(0, 120)"> <line x1="0" y1="0" x2="270" y2="0" /> <text x="-30" y="20">January 2014</text> <text x="240" y="20">April</text> </g> </g> </svg>

5. Reference