Open In App

How to import a SVG file in JavaScript ?

SVG (Scalable Vector Graphics) files in JavaScript are XML-based vector image files commonly used for describing two-dimensional vector graphics. In this article, we are going to see and use different ways of using SVGs.

Below are the methods to import an SVG file in JavaScript:



Using HTML img element

To include an SVG file in an HTML document using the img element, you can set the src attribute of the img tag to the path of the SVG file.



Syntax:

 <img src='logo.svg' alt="some file"  height='100'
width='100' style="color:green;"/>

Embedding an SVG through the <img> element, you need:

Pros:

Cons:

Example: In this example, we are using img tag for using SVG.




<!DOCTYPE html>
<html lang="en">
  <body>
    <img
      src=
      alt="gfg-logo"
      height="100"
      width="100"
      style="background-color: green"
    />
  </body>
</html>

Output :

SVG file using HTML <img> element

Using SVG as an object tag

To include an SVG file in an HTML document using the <object> tag, you can specify the SVG file’s path in the data attribute. This method allows for more direct interaction with the SVG content.

Syntax: 

<object type="image/svg+xml" data="logo.svg" class="logo">
  Logo
</object>

Embedding a SVG via a <object> element requires:

Pros:

Cons:

Example: In this example, we are using object tag for using SVG.




<!DOCTYPE html>
<html lang="en">
<body>
  <object type="image/svg+xml"
          data=
          class="logo">
    GFG Logo
  </object>
  
</body>
  
</html>

Output:

SVG file using HTML element

Embedding an SVG with an iframe tag

To embed an SVG file in an HTML document using the <iframe> tag, you can set the src attribute to the path of the SVG file. This method is similar to using the <img> tag but allows for more flexibility in terms of interaction and styling.

Syntax:

<iframe src="logo.svg" width="500" height="500">

</iframe>

Embedding a SVG via <iframe> element requires

Pros:

Cons:

Example: In this example, we are using iframe tag for using SVG.




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,
                                   initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
  </head>
 
  <body>
    <iframe
      src=
      width="150"
      height="150">
    </iframe>
  </body>
</html>

Output:


Article Tags :