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+)
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+)
Share Improve this question asked Feb 1, 2016 at 5:44 Steve BennettSteve Bennett 127k45 gold badges186 silver badges243 bronze badges 02 Answers
Reset to default 6document.createElementNS creates an SVG element, so to create a rect element you'd write.
var rect = document.createElementNS('http://www.w3/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.
DYNAMICALLY DRAW AN ORANGE RECTANGLE ON AN SVG
-document.createElementNS
to create the element
-<element>.setAttribute
to give it attributes
-svg.appendChild(<element>)
to add it to the SVG on the DOM
<script type="text/javascript">
var mainSVG = document.querySelector('svg');
var selRectangle = document.createElementNS('http://www.w3/2000/svg', 'rect');
selRectangle.setAttribute('x', 5);
selRectangle.setAttribute('y', 5);
selRectangle.setAttribute('width', 20);
selRectangle.setAttribute('height', 20);
selRectangle.setAttribute('class', 'selRect');
mainSVG.appendChild(selRectangle);
</script>
<style type="text/css">
.selRect{
fill: orange;
stroke: orange;
stroke-width: 2px;
fill-opacity: 0.1;
stroke-opacity: 0.7;
}
</style>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744501950a4577485.html
评论列表(0条)