I'm trying to create a dynamically construct an SVG document, and hoping to avoid having to actually write <rect ...>
etc. After creating the SVG document, Chrome shows that it has methods like createSVGRect()
, createSVGPoint()
etc. The former seems to take no arguments, and returns an SVGRect
object with just the properties x
, y
, width
and height
.
Strangely, it's hard to find documentation on these methods. MDN states:
Creates an SVGRect object outside of any document trees. The object is initialized such that all values are set to 0 user units.
It doesn't give any indication how you would apply a style to it, or insert it into an SVG DOM.
So...if that's not the way to create a rect
element in an SVG document, what is?
(I need to support IE9+)
document.createElementNS creates an SVG element, so to create a rect element you'd write.
var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
The type of object created above is an SVGRectElement.
An SVGRect object is not an SVG element, it's just something passed into or returned by some SVG DOM methods e.g. getBBox.