Home > Back-end >  Embed SVG image in HTML and keep text as text
Embed SVG image in HTML and keep text as text

Time:08-28

Consider an SVG image with text. Is it possible to embed it into an HTML document using an image tag (or any other) and keep the text as text, so it can be selected or searched for e.g. using "control find"?

A plain image tag does not achieve this:

<image src="https://www.w3.org/TR/SVG11/images/text/toap04.svg"></image>

CodePudding user response:

You have a couple of options when embedding an SVG with selectable text.

Inline SVG

You can embed an inline SVG in an HTML document using the <svg> tag.

    <svg width="453px" height="136px" viewBox="0 0 1000 300">
  <defs>
    <path id="MyPath" d="M 100 125 
                 C 150 125 250 175 300 175
                 C 350 175 450 125 500 125
                 C 550 125 650 175 700 175
                 C 750 175 850 125 900 125" />
  </defs>
  <use xlink:href="#MyPath" fill="none" stroke="red" />
  <text font-family="Verdana" font-size="60" fill="blue" letter-spacing="2">
    <textPath xlink:href="#MyPath">
      Choose shame or get war
    </textPath>
  </text>
  <rect x="1" y="1" width="998" height="298" fill="none" stroke="blue" stroke-width="2" />
</svg>

<object> tag

You can also use the <object> tag when linking to an external SVG.

<object data="https://www.w3.org/TR/SVG11/images/text/toap04.svg" width="453" height="136"></object>

CodePudding user response:

You can load any external file, and inline it, with the <load-file> (native javascript) Web Component.

Loads of options, unlicensed and only 8 lines of code:
Dev.To blog post <load-file> Web Component

<script src="https://load-file.github.io/element.js"></script>
 
<load-file replaceWith src="https://www.w3.org/TR/SVG11/images/text/toap04.svg"></load-file>

<style>
  svg{ background:lightgreen }
  rect { stroke:green; stroke-width:60; rx:60 }
</style>

  • Related