How can I display HTML within an SVG document?

2019-06-06 13:57发布

I have SVG documents which I display directly in browsers (currently IE and Firefox) - by loading the *.svg directly into the browser. These documents contain text which I would like to display as "HTML", e.g. rendered in an HTML window/panel with word-wrap, subscripts and possibly scrolling. The SVG and HTML are well formed and managed under the correct namespaces.

A typical sort of element (without styles) might be:

<svg  xmlns="http://www.w3.org/2000/svg">
  <g>
    <rect x="100" y="200" width="300" height="400"/>
    <h:p xmlns:h="http://www.w3.org/1999/xhtml">
This is an <h:i>italic</h:i> and a <h:sub>subscript</h:sub> in a ...
very long ... paragraph which will need word wrapping and maybe scrolling
    </h:p>
  </g>
</svg>

It would be nice to be able to locate the text within a given bounding box (e.g. the <rect/>)

Note that at present I do not want to embed SVG within an HTML document and there is no need for recursion (e.g. no SVG within the HTML).

UPDATE: Encouraged by @Sirko I found this article on the web it's 4 years old.

标签: html svg
2条回答
淡お忘
2楼-- · 2019-06-06 14:11

In general the <foreignObject> shall be used for including different markups inside of SVG (see MDN docu on this). In your case this other markup would be XHTML.

<svg  xmlns="http://www.w3.org/2000/svg">
  <g>
    <rect x="100" y="200" width="300" height="400" style="fill: none; stroke: black; stroke-width: 1px;"/>
    <foreignObject x="100" y="200" width="300" height="400">  
      <!-- XHTML content goes here -->  
      <body xmlns="http://www.w3.org/1999/xhtml">  
        <p>
            This is an <i>italic</i> and a <sub>subscript</sub> in a ...
            very long ... paragraph which will need word wrapping and maybe scrolling
        </p>
      </body>  
    </foreignObject>  

  </g>
</svg>

This, however, has quite some compatibility problems between the major browsers!

查看更多
对你真心纯属浪费
3楼-- · 2019-06-06 14:14

Not only can you include HTML in SVG, but you can even include HTML in SVG in HTML in SVG in HTML ...

Here's some example code from HTML in SVG in HTML :

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>HTML in SVG in HTML</title>
  <style type='text/css'>
    svg { border: 1px solid black; }
    svg div { border: 1px dotted blue; }
  </style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" width="800" height="500">
  <foreignObject class="node" x="46" y="22" width="200" height="300">
    <body xmlns="http://www.w3.org/1999/xhtml">
      <div>The quick brown fox jumps over the lazy dog. Pack my box with
         five dozen liquor jugs</div>
    </body>
  </foreignObject>
</svg>
</body>
</html>

Still, note that support for inline SVG in HTML documents remains "quirky" at best, even today (March 2014). For example, try this Codepen in different browsers.

查看更多
登录 后发表回答