Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create SVG tag with JavaScript

Tags:

javascript

svg

How do I create an SVG element with JavaScript? I tried this:

var svg = document.createElement('SVG');     svg.setAttribute('style', 'border: 1px solid black');     svg.setAttribute('width', '600');     svg.setAttribute('height', '250');     svg.setAttribute('version', '1.1');     svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); document.body.appendChild(svg); 

However it creates an SVG element with zero width and zero height.

like image 315
Richard Avatar asked Nov 21 '11 16:11

Richard


People also ask

How to add JavaScript code to an SVG file?

For an external SVG, you can use the same code when adding the <script> element into the SVG itself. However, you may want to wrap the code with CDATA. If you don't, then the XML parse will consider the JS code part of XML, and if you use < or >, it will break (as in this example), thinking you're trying to start or end a tag.

What is an SVG tag?

Definition and Usage The <svg> tag defines a container for SVG graphics. SVG has several methods for drawing paths, boxes, circles, text, and graphic images. To learn more about SVG, please read our SVG Tutorial.

Is it possible to add an empty SVG element in HTML?

All of the following demos have an empty SVG element in the HTML. I’ve manually added it, but you can create and add it via JavaScript as well. I also used a background rectangle so we can see what we’re doing.

Can You dynamically create SVG elements?

You can dynamically create curves and paths too, but that’s a bit more involved so I’ll save it for another tutorial. I hope you picked up a few pixels of information about creating dynamic SVG elements. Until next time, keep your pixels movin’.


1 Answers

You forgot the Namespace URI of your svg element and xmlns attribute.

Also, version is ignored by all browsers.

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");     svg.setAttribute('style', 'border: 1px solid black');     svg.setAttribute('width', '600');     svg.setAttribute('height', '250');     svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");     document.body.appendChild(svg);
like image 157
TeChn4K Avatar answered Sep 22 '22 00:09

TeChn4K