Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append foreignObject containing some HTML inside an SVG element

Is there any way to append a foreignObject element containing some simple HTML to an svg element? Here's the code I tried:

 var foreignObject = document.createElement('foreignObject');
 foreignObject.setAttribute('height', '300');
 foreignObject.setAttribute('width', '300');
 var div = document.createElement('div');
 div.innerHTML = 'Hello World';
 foreignObject.appendChild(div); 
 svg.appendChild(foreignObject); //svg is an already created svg element containing a d3 chart

But the svg remains the same even after this code executes. Is there anything else that I need to do?

like image 253
Tarun Dugar Avatar asked Jul 18 '16 13:07

Tarun Dugar


People also ask

How to add HTML inside SVG?

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.

Can you render HTML inside SVG?

This can be solved by using the <foreignObject> SVG element in which you can add an HTML under a different namespace than the parent SVG and then you can also style the elements using CSS like so.

Can SVG contain embedded audio?

SVG supports embedded content with the use of 'image' and 'foreignObject' elements. Additionally SVG allows embedded content using HTML 'video', 'audio', 'iframe' and 'canvas' elements.


2 Answers

You don't need document.createElementNS or document.createElement, you can simply append the foreignObject using your D3 selection.

This is an example borrowed from Bostock, D3 creator:

<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var svg = d3.select("body").append("svg")
    .attr("width", 960)
    .attr("height", 500);
svg.append("foreignObject")
    .attr("width", 480)
    .attr("height", 500)
  .append("xhtml:div")
    .style("font", "14px 'Helvetica Neue'")
    .html("<h1>An HTML Foreign Object in SVG</h1><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. ");
</script>
like image 100
Gerardo Furtado Avatar answered Sep 28 '22 05:09

Gerardo Furtado


You forgot to attach the namespace to the <foreignObject> Element:

var ns = 'http://www.w3.org/2000/svg';
var svg = document.querySelector( 'svg' );

var foreignObject = document.createElementNS( ns, 'foreignObject');
foreignObject.setAttribute('height', 300);
foreignObject.setAttribute('width', 300);

var div = document.createElement('div');
div.innerHTML = 'Hello World';

foreignObject.appendChild( div ); 
svg.appendChild(foreignObject); //svg is an already created svg element containing a d3 chart
<svg></svg>
like image 21
Sirko Avatar answered Sep 28 '22 04:09

Sirko