Generate SVG elements using JavaScript
P粉662802882
2023-08-22 22:04:39
<p>How to create an SVG element using JavaScript? I tried the following code: </p>
<pre class="brush:php;toolbar:false;">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);</pre>
<p>However, it creates SVG elements with zero width and zero height. </p>
.createElementNS
is a required method forsvg
andpath
elements. Below are examples.You forgot the
namespace URI
and xmlns attributes of yoursvg
element.Additionally, the
version
attribute is ignored by all browsers.