问题
I'm using d3, and I'd like to use the getBBox method that SVG elements have.
I'm using the following: (d3Selection.node() as SVGElement).getBBox(), however the TypeScript fails to compile due to the error in the title.
Is SVGElement the wrong type to use? I can it working using any instead, but this seems like a bit of an "unclean" solution.
回答1:
Not all SVG elements have bounding boxes, <defs> for instance doesn't, neither does <title>, so yes SVGElement is the wrong type to use. You want SVGGraphicsElement
回答2:
Instead of SVGElement, SVGSVGElement is the correct type to use for accessing <svg> elements, where getBBox() method is available as well because of the inheritance from SVGGraphicsElement.
(d3Selection.node() as SVGSVGElement).getBBox()
Or if d3Selection is defined as
let d3Selection: D3.Selection<SVGSVGElement, {}, HTMLElement, any>
d3Selection.node().getBBox()
could be directly into usage.
来源:https://stackoverflow.com/questions/45792692/property-getbbox-does-not-exist-on-type-svgelement