Developing Web applications using SVG images can be done in the following four ways:

1. Insert the page directly. 2. The IMG label is imported. 3. CSS introduction. 4. The object label is imported.Copy the code

1. Insert the page directly

In HTML pages, you can use SVG tags directly.

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<! -- an SVG image -->
		<svg width="200" height="150" style="border: 1px solid steelblue">
			<! -- There is a rectangle inside -->
			<rect x="10" y="10" width="100" height="60" fill="skyblue"></rect>
		</svg>
	</body>
</html>
Copy the code

Operation effect:

2. The IMG label is imported

In addition to writing SVG tags directly on a web page, img can also be introduced, just like JPEG and PNG images.

1) Create a new SVG image

We will create a new SVG image file and use the SVG directly in the web:

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="150">
	<rect x="10" y="10" width="100" height="60" fill="skyblue"></rect>
</svg>
Copy the code

There are two differences here:

1. You need to declare the XMLNS namespace property, which is listed in Resources at the end of this article. 2. Remove the style originally written on the SVG tag, style="border: 1px solid steelblue".Copy the code

Save the content to the test. SVG file, which is an image file, and try opening it in your browser.

2) Use the IMG tag to import

Assume that test.svg and the web page file are in the same directory:

<img src="test.svg" style="border: 1px solid steelblue" />
Copy the code

Similar to the introduction of JPEG and PNG, the SRC attribute sets the image path directly, and we move the SVG style to the IMG tag.

It works the same as above:

There are many SVG images on the web now, you can refer to: www.iconfont.cn, a good icon website.

3. The CSS

CSS import is to import an image as a background:

<style type="text/css">
	.svg {
		width: 200px;
		height: 150px;
		border: 1px solid steelblue;
		background-image: url(test.svg); // as background}</style>
<div class="svg"></div>
Copy the code

4. Introduced object

Like img, you need an SVG file and use the property data to import:

<object data="test.svg" style="border: 1px solid steelblue"></object>
Copy the code

Run the same effect as above, no longer map.

Other tags

Other tags, such as embed and iframe, can also be introduced but are not recommended. See resources at the end of this article for details.

The resources

  1. Namespace: developer.mozilla.org/zh-CN/docs/…
  2. Embed tag: developer.mozilla.org/zh-CN/docs/…
  3. Iframe tag: developer.mozilla.org/zh-CN/docs/…