How to add SVG to a webpage

Source: Internet
Author: User
Tags processing instruction

This topic describes common ways to present SVG on a webpage and assumes that you have basic knowledge about html and JavaScript.

  • Introduction
  • SVG Rendering Method
    • Inline HTML5
    • Inline XHTML
    • Independent SVG
    • Embedded
    • Plug-ins
  • Summary
  • Related Topics
Introduction

If you only know about Scalable Vector Graphics (SVG) and want to experience SVG, one of the first issues you need to solve is how to add SVG to basic webpages. If you look at the basic web page template, you can learn how to start this operation.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

You can add SVG to this basic template in multiple ways. The following example demonstrates a method for directly performing this operation.

<?xml version="1.0" encoding="utf-8" standalone="no"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

PromptTo improve compatibility between modern browsersxhtmlSave the file extension. By transferring the file extension fromhtmlChange
xhtmlTo effectively convert a template from an HTML document to An XHTML document. This is whyxmlDeclare (the first line in the previous example) and comment out
metaElement. For more information about the previous example, see the following list.

<?xml version="1.0" encoding="utf-8" standalone="no"?>

xmlA statement is a browser Processing Instruction that identifies a document as XML/xhmtl. The required version feature specifies the XML standard version that the XML document will follow. OptionalencodingThe feature instructs the browser how to interpret the associated byte of a document based on a specific character set (which is encoded as a UTF-8 by default ). Optional
standalone="no"Feature indication inDOCTYPEThe document type definition (DTD) specified in the element is not only used for verification. Note that you do not need to specify
standalone=”no”. When an external tag Declaration exists (DTD in this example), it is assumed thatstandalone=”no”Value.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Technically speaking,DOCTYPEThe Declaration is not an HTML element. This statement is a description of Web browsers. It introduces the markup language version for writing pages. Note that this Declaration is used to specify the DTD of the markup language rule so that the browser can correctly render the content. Doctype also allows you to use the page verification program. In this example, XHTML 1.0 transitional
DTD enables all HTML elements and features, including representation elements and discarded elements (for example<font>). However, the framework is not allowed and the markup must be written into XML in the correct format.

htmlThe element tells the browser that this is an HTML document in the general sense. Specifically, it is composedDOCTYPEIndicates the XHTML document.xmlns
Feature specifies the XML namespace Of The XHTML document. Generally, developers should explicitly include the XHTML xmlns declaration when writing XHTML documents.

Use
headYou can define the page title, provide search engine information, set the page location, add a style sheet, and write scripts. (For examplebase,link,meta,scriptAnd
style).

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

metaThe element provides metadata about the document. Metadata is information about the document content (invisible to readers ). This metadata is available for browsers or other software (such as search engines and document management systems. The first template (does not havesvgElement). Before the Server transfers the actual page content, use the name
Content-Type(The value istext/html; charset=utf-8) To provide the page (from the Web server to the client ). With this process, the browser can use the correct character encoding (charset = UTF-8) to normally present incoming page data (text/html ). The second XHTML (SVG) example is commented out.metaElement, because the XML/xhml file is ignored
metaThe element specifies the character encoding and must be convertedxmlStatement. Developers can usemetaElements and use of XML/XHTML
xmlSwitch between declarations.

<title>

Generally,titleThe associated text of the element is displayed on the tab of the browser.

head.

<body>

bodyThe element is the container for displaying the content of the XHTML document.

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

svgThe element defines the SVG document snippets.xmlnsThe feature defines the namespace of the SVG fragment.versionFeature indicates the SVG language version that this document snippet follows,widthAndheight
The feature defines the size of the SVG area (in this example, it is a 200x200 pixel square ).

<rect x="0" y="0" width="100%" height="100%" fill="none" stroke="black"/>

SVG
rectThe element draws a black rectangle with the maximum width and height from the upper left corner of the area or from the point (0, 0). The rectangle is opposite to the SVG area. This location outlines the profile of the given SVG area.

<circle cx="100" cy="100" r="50" style="stroke: black; fill: red;"/>

Similarly, SVG
circleThe element draws a red circle with a black border with a radius of 50 pixels. The circle is located at the center of the SVG video area of 200x200 pixels.

</svg>

svg.

</body>

body.

html.

SVG Rendering Method

You can also use other methods to render SVG. The following table summarizes these methods.

Method Recommended File Extension Required browsers Advantages and disadvantages
Inline HTML5 . Html Supports built-in SVG browsers in HTML5, such as Windows Internet Explorer 9.

Advantage: You can make full use of html5.

Disadvantage: you may need to implement callback code for browsers that do not support inline SVG in HTML5.

Inline XHTML . XHTML Local browsers that support SVG, such as Internet Explorer 9.

Advantage: Many browsers currently support XHTML-based inline SVG.

Disadvantage: HTML5 cannot be used for construction.

Independent . SVG Local browsers that support SVG, such as Internet Explorer 9.

Advantage: You can use the "embed" method to easily embed existing content.

Disadvantage: All html/XHTML structures cannot be used.

Embedded . XHTML Local browsers that support SVG, such as Internet Explorer 9.

Advantage: embedding makes implementation and callback relatively simple.

Disadvantage: it may be difficult to write scripts for SVG content embedded in pages. In addition, some browsers may not support all forms of embedding, suchimgElement or through CSSbackground-imageStyle references SVG.

Plug-ins . Html It may be locally supported or not locally supported by SVG browsers.

Advantage: the browser does not need to support SVG locally. Unify the SVG behavior between browsers.

Advantage: plug-ins may cause browser instability, W3C SVG specifications may be outdated, and/or plug-in providers no longer support plug-ins (such as the Adobe SVG Viewer plug-in ).

Note:Windows Internet Explorer 8 does not support SVG locally, so it requires a plug-in to render SVG. However, by implementing the appropriate callback code (as described later in this topic), you may not need the SVG plug-in.

The next section describes the examples of the above five methods.

Inline HTML5

The following example demonstrates a basic inline HTML5 SVG template. This sample code creates a circle in the SVG tag and registers the click event. When you click the circle, its size changes.

<!DOCTYPE html>

<!DOCTYPE html>Element tells the browser that this is an HTML5 document.<meta http-equiv="X-UA-Compatible" content="IE=9"/>Element is used to force Windows Internet Explorer to ie9 standard mode, so that it can be correctly displayed on an Intranet website. Please note that HTML5 applications cannot be appliedhtmlElement
xmlns="http://www.w3.org/1999/xhtml"Features.

PromptAs recommended in the preceding tablehtmlFile Extension save this example.

Note:For HTML5, SVG content overflows by default, but it is hidden in XHTML.

Inline XHTML

Because SVG is based on XML, you can use the correct namespace to add SVG to the XHTML document, as shown in the following basic inline XHTML template.

<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

This code example creates a 200x200 pixel view area and draws a red circle with a black border with a radius of 50px. If you move the mouse pointer over the displayed circle, the circle radius is doubled. If you move the mouse pointer from the displayed circle, the current circle radius is halved. The rectangle element is used to outline the border of the area.

PromptAs recommended in the preceding tablexhtmlFile Extension save this example.

Inline XHTML works normally, but requiresxhtmlFile Extension and namespace. Before HTML5 appeared recently, inline XHTML was the best choice.

Independent SVG

SVG was originally designed to usesvgFile Extension to provide vector graphics file formats. The following example demonstrates a basic independent SVG template.

<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"                      "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg width="100%" height="100%" version="1.1"      xmlns="http://www.w3.org/2000/svg"     xmlns:xlink="http://www.w3.org/1999/xlink"     onclick="doSomething(evt)">    <script language="javascript" type="text/javascript">  <![CDATA[    function doSomething(evt)     {      var myRect = evt.target;        if (myRect.id != "redRect")       {        alert("Please click on the rectangle");        document.location.reload();      }        var myWidth = myRect.getAttribute("width");            if (myWidth == 50)        myRect.setAttribute("width", 100);      else        myRect.setAttribute("width", 50);    }     ]]>  </script>  <!-- Outline the SVG viewport. -->  <rect x="0" y="0" width="100%" height="100%"         style="fill: none; stroke: black; stroke-width: 5px;" />     <rect id="redRect" x="100" y="100" width="50" height="50"         fill="red" stroke="blue" />    </svg>

This code example uses an internal click to alternately expand or contract the red rectangle. If you click outside the red rectangle, a warning is displayed and the page is reloaded.

As described above
In the XML Element (the first line ),standalone="no"Feature indication,DOCTYPEThe DTD specified in the element is not only used for verification. You do not need to specifystandalone=”no”Because this value is assumed when an external tag Declaration exists (DTD in this example.

PromptAs recommended in the preceding tablesvgSave this example with the extension.

Embedded

You can useiframe,embed,objectAnd
img
Elements and CSSbackground-imageStyle: Embed SVG into a webpage. Note that not all of these embedding methods can be used in a specific browser. The following example demonstrates the basic SVG template, which usesobjectElement.

<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

PromptAs recommended in the preceding tablexhtmlFile Extension save this example. You must also note that the SVG file is embedded (in this examplestandAlone.svg) Must have
svgFile extension.

Assume that the SVG file does not passimgElement embedding is not embedded as a CSS background. embedding an SVG file usually has its own programming method, unless the embedded SVG file comes from the same domain as the embedded page, otherwise, embedding does not provide a simple method for programmable interaction between an embedded SVG document and an embedded HTML document. We recommend that you do not use this method when programming SVG on a web page, but this method can be used to easily insert an SVG file and, local Internet Explorer 8 does not support SVG.

Note:Some browsers cannot support all forms of SVG embedding, so be sure to test across all target browsers.

Plug-ins

The following lists the reasons why plug-in solutions are not recommended:

  • Adobe no longer supports the main SVG browser plug-in Adobe SVG viewer.
  • Most modern browsers support SVG locally.
  • Third-party plug-ins may cause browser instability, or plug-in providers no longer provide support for them.
Summary

The following table summarizes the templates viewed in this topic.

Method Template Recommended File Extension Recommended servers
Mime Type
Inline HTML5

<!DOCTYPE html>
. Html Text/html
Inline XHTML

<?xml version="1.0"?><!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
. XHTML Application/XHTML + XML
Independent

XML
<?xml version="1.0"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg width="100%" height="100%" version="1.1"      xmlns="http://www.w3.org/2000/svg"     xmlns:xlink="http://www.w3.org/1999/xlink">       <!-- SVG markup here. -->      </svg>
. SVG Image/SVG + XML
Embedded

<?xml version="1.0"?><!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
.Xhtml#.html Text/html
Plug-ins Not recommended. . Html Not recommended.

Note:Microsoft Internet Information Service (IIS) is not used by default.
.svg
Provides services for files with file extensions. To request from IIS.svgWeb page, you must.svg"MIME type" ingimage/svg+xml.

For browsers that support SVG and HTML5 locally, it is best to use the inline HTML5 method.

For browsers that do not fully support HTML5 but support SVG locally, use the inline XHTML or independent method, followed by the embedding method (if applicable ).

For browsers that do not support SVG locally, it is recommended to implement corresponding callback measures (for example, rendering static images of SVG images ).

Use<meta http-equiv="X-UA-Compatible" content="IE=9"/>Enables Scalable Vector Graphics (SVG) for HTML applications (HTA ). For more information, see Introduction to HTML applications (HTA.

Related Topics
How to Use SVG for scaling and moving
SVG
SVG reference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.