4 ways to introduce svg images into shared html pages

This article mainly introduces 4 ways to introduce svg images into html webpages. The article introduces in great detail through sample codes, which has a certain reference learning value for everyone's study or work. Friends who need it, follow the micro-point reading editor to come together learn to learn

Web application development uses svg images. In summary, there are four ways:

1. Insert directly into the page.
2. Import the img tag.
3. CSS introduction.
4. The object tag is introduced.

1. Insert directly into the page

In the html page, you can directly use the svg tag.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<!DOCTYPE html>

<html>

    <head>

        <meta charset="utf-8">

        <title></title>

    </head>

    <body>

        <!-- 一个svg图片 -->

        <svg width="200" height="150" style="border: 1px solid steelblue">

            <!-- 里面有一个矩形 -->

            <rect x="10" y="10" width="100" height="60" fill="skyblue"></rect>

        </svg>

    </body>

</html>

running result:

2. Import the img tag

In addition to directly writing svg tags in the web page, it can also be imported through img, just like importing jpeg and png images.

1) Create a new svg image

Then we need to create a new svg image file first, and we use the svg written directly on the web page:

1

2

3

<svg xmlns="SVG namespace" width="200" height="150">

    <rect x="10" y="10" width="100" height="60" fill="skyblue"></rect>

</svg>

There are two differences here:

1. You need to declare the namespace xmlns attribute, which can be referenced at the end of this article.
2. Removed the style originally written on the svg tag, style="border: 1px solid steelblue".

Save the content to the test.svg file, this is a picture file, you can try to open it in the browser.

2) Use the img tag to import

Assuming that test.svg and the webpage file are in the same directory:

1

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

Similar to importing jpeg and png, you can directly set the image path with the src attribute. In addition, we moved the original svg style to the img tag.

3. css import

The css import is to import the image as a background image:

1

2

3

4

5

6

7

8

9

<style type="text/css">

    .svg {

        width: 200px;

        height: 150px;

        border: 1px solid steelblue;

        background-image: url(test.svg); // 当成背景引入

    }

</style>

<div class="svg"></div>

4. Object introduction

Similar to importing img, an svg file is required, and then imported with the attribute data:

1

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

The running effect is similar to the above, no more textures.

other tags

Other tags such as: embed, iframe tags can also be introduced, but they are not recommended

Reprinted from: Weidian Reading    https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/130743948