开发者

Creating inline SVG with JS in HTML5

开发者 https://www.devze.com 2023-01-23 16:37 出处:网络
I\'m working with a local HTML5 file -- it\'s got <!DOCTYPE html> at the top.I put something like this in it:

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?


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. :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消