javascript 获取 Rect 元素的屏幕像素坐标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5834298/
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
Getting the Screen Pixel coordinates of a Rect element
提问by Matthias
I am trying to get the screen pixel coordinates of a rectangle in SVG via java script. When the rectangle has been clicked, I can figure out its width, height, x and y position with getBBox().
我正在尝试通过 java 脚本获取 SVG 中矩形的屏幕像素坐标。单击矩形后,我可以使用 getBBox() 计算出它的宽度、高度、x 和 y 位置。
But these positions are the original positions. I want the screen position.
但这些位置都是原来的位置。我想要屏幕位置。
For example if I manipulate the viewBox of the whole SVG, these getBBox coordinates are not any more the same than the screen pixels. Is there a function or way to get the coordinates considering the current viewBox and the pixel size of svg element?
例如,如果我操作整个 SVG 的 viewBox,这些 getBBox 坐标与屏幕像素不再相同。考虑到当前 viewBox 和 svg 元素的像素大小,是否有获取坐标的函数或方法?
回答by Phrogz
Demo: http://phrogz.net/SVG/screen_location_for_element.xhtml
演示:http: //phrogz.net/SVG/screen_location_for_element.xhtml
var svg = document.querySelector('svg');
var pt = svg.createSVGPoint();
function screenCoordsForRect(rect){
var corners = {};
var matrix = rect.getScreenCTM();
pt.x = rect.x.animVal.value;
pt.y = rect.y.animVal.value;
corners.nw = pt.matrixTransform(matrix);
pt.x += rect.width.animVal.value;
corners.ne = pt.matrixTransform(matrix);
pt.y += rect.height.animVal.value;
corners.se = pt.matrixTransform(matrix);
pt.x -= rect.width.animVal.value;
corners.sw = pt.matrixTransform(matrix);
return corners;
}
The magenta squares are absolutely-positioned divs in the HTML element, using screen space coordinates. When you drag or resize the rectangles this function is called and moves the corner divs over the four corners (lines 116-126). Note that this works even when the rectangles are in arbitrary nested transformation (e.g. the blue rectangle) and the SVG is scaled (resize your browser window).
洋红色方块是 HTML 元素中绝对定位的 div,使用屏幕空间坐标。当您拖动矩形或调整矩形的大小时,将调用此函数并将角 div 移动到四个角上(第 116-126 行)。请注意,即使矩形处于任意嵌套转换(例如蓝色矩形)并且 SVG 已缩放(调整浏览器窗口的大小),这也有效。
For fun, drag one of the rectangles off the edge of the SVG canvas and notice the screen-space corners staying over the unseen dots.
为了好玩,将其中一个矩形拖离 SVG 画布的边缘,并注意屏幕空间角落停留在看不见的点上。
回答by Erik Dahlstr?m
You can also check for the existence of the elm.getScreenBBox()
method, which does what it sounds like. It's defined in SVG Tiny 1.2.
您还可以检查该elm.getScreenBBox()
方法是否存在,它听起来像什么。它在SVG Tiny 1.2 中定义。
See the files here, which include a fallback implementation of getScreenBBox
that should work in all browsers.
请参阅此处的文件,其中包含getScreenBBox
应适用于所有浏览器的回退实现。