Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating inline SVG with JS in HTML5

I'm working with a local HTML5 file -- it's got <!DOCTYPE html> at the top. I put something like this in it:

<svg height="2em" width="3em" preserveAspectRatio="none" viewBox="0 0 100 100">
  <rect x="0" y="0" width="100" height="100" fill="red"/>
</svg>

(no namespaces, thanks HTML5!), and it displays great in Chrome and FF4 beta.

Now I want to create the same thing but via JS. I'm using Prototype, so I wrote something like:

var box = new Element('svg', {'width':'3em', 'height':'2em', 'preserveAspectRatio': 'none', 'viewBox': '0 0 100 100'});
box.appendChild(new Element('rect', {fill:'red', x:'0', y:'0', width:'100', height:'100' }));
container.appendChild(box);

I can see in Firebug / DOM inspector (both FF and Chrome) that it's creating the same DOM structure for this.

The only difference I see is that the attributes ("preserveAspectRatio" and "viewBox") are all-lowercase, but I tried changing the attributes in my first test (static HTML) to all-lower-case and it still works fine, so I don't think that's the problem.

Is the HTML5 SVG capability limited to static HTML, and I need to do namespaces still for adding SVG content via JS, or is there something else I'm missing?

like image 570
Ken Avatar asked Nov 07 '10 05:11

Ken


1 Answers

Turns out it was a namespace issue: the elements need to be created with createElementNS("http://www.w3.org/2000/svg", ...), which Prototype happens to have no built in (new Element(...)) support for. So I guess the HTML5 SVG situation is basically "SVG without a namespace gets the namespace added during parsing (but after that it's just like XHTML before)".

P.S., the "Answer Your Question" button here isn't working for me today, so if anybody adds this as as answer, I'll mark it correct. :-)

like image 64
user30932 Avatar answered Nov 04 '22 09:11

user30932