Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG foreignObject contents do not display unless plain text

Tags:

html

svg

d3.js

I am trying to output HTML using the foreignObject tag inside an SVG drawing. I am using d3 to generate the elements. The only time the HTML content inside the foreignObject tag shows up is when the content inside the foreignObect tag is plain text, otherwise it just shows up as empty/blank. Please see this jsfiddle for an example of my problem: http://jsfiddle.net/R9e3Y/29/

The contents inside the foreignObject tag show up on inspecting the element this this:

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">     <foreignObject x="40" y="40" width="100" height="100">         <div>test</div>     </foreignObject> </svg>  

but are not visible on the screen? How do I get the content to show up?

like image 954
Atomix Avatar asked Dec 12 '12 20:12

Atomix


2 Answers

Since you're using d3 you need to tell d3 that the div is a html div and not some element in the svg namespace. Try

.append("xhtml:div") 
like image 94
Robert Longson Avatar answered Sep 21 '22 20:09

Robert Longson


<foreignObject> allows embedding all kinds of markup, not just HTML. This means, there must be a way of determining what language is used. That's where namespaces come into play.

To tell SVG what kind of foreignObject you have, you have to put the content in the proper namespace.

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">   <foreignObject x="40" y="40" width="100" height="100">     <div xmlns="http://www.w3.org/1999/xhtml">test</div>   </foreignObject> </svg>  

In your example, the <div> element is in the SVG namespace, i.e. it's an SVG element, not an HTML one (albeit a non-standard one).

The <foreignObject> element also has a requiredExtensions attribute to tell the browser which extension is used, however different browsers seem to be interpreting this attribute differently, so it's probably best to not set it.

like image 31
Thomas W Avatar answered Sep 20 '22 20:09

Thomas W