javascript 获取选定 SVG 元素的边界框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14926180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the bounding box of a selected SVG element
提问by nicholaswmin
I want to read:
我想阅读:
width
,height
,x
,y
measurements
width
,height
,x
,y
测量
for a particular SVG element.
对于特定的 SVG 元素。
I suppose that easiest way to go about this is to fetch the minimum bounding boxfirst and read it's properties.
我想最简单的方法是首先获取最小边界框并读取它的属性。
How can I access this?
我怎样才能访问这个?
采纳答案by Bellave Jayaram
Assuming you have a handle to the element, I would think that this would work, no?
假设你有一个元素的句柄,我认为这会起作用,不是吗?
box = svgedit.utilities.getBBox(selected);
回答by pawel
If you have a reference to the DOM node, use
如果您有对 DOM 节点的引用,请使用
svgNode.getBoundingClientRect()
https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect
https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect
Edit: SVG Edit has a methodto return currently selected elements:
编辑:SVG Edit 有一个方法可以返回当前选中的元素:
svgCanvas.getSelectedElems()
so in the above example:
所以在上面的例子中:
svgNode = svgCanvas.getSelectedElems()[0];
svgNode.getBoundingClientRect();
回答by MSC
Please see http://granite.sru.edu/~ddailey/svg/BBox0M.svgfor the example and answer.
有关示例和答案,请参阅http://granite.sru.edu/~ddailey/svg/BBox0M.svg。
In brief, this code works for me in Chrome:
简而言之,这段代码在 Chrome 中对我有用:
<script>
function foo(evt)
{
console.log(evt.target.getBBox());
}
</script>
<svg>
<circle onclick="foo(evt)" r="20%" cx="50%" cy="50%"/>
</svg>
回答by turiyag
I'm not sure if I'm understanding you correctly, but if you're looking to get the height or width of a jQuery element, use width() and height():
我不确定我的理解是否正确,但是如果您想获取 jQuery 元素的高度或宽度,请使用 width() 和 height():
log("The svg is " + $("img").width() + "px wide.");
log("The svg is " + $("img").height() + "px tall.");
JSFiddle example: http://jsfiddle.net/gGWU4/
JSFiddle 示例:http: //jsfiddle.net/gGWU4/