获取 Rect 元素的屏幕像素坐标 [英] Getting the Screen Pixel coordinates of a Rect element

查看:60
本文介绍了获取 Rect 元素的屏幕像素坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 java 脚本获取 SVG 中矩形的屏幕像素坐标.单击矩形后,我可以使用 getBBox() 计算出它的宽度、高度、x 和 y 位置.

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().

但这些位置都是原来的位置.我想要屏幕位置.

But these positions are the original positions. I want the screen position.

例如,如果我操作整个 SVG 的 viewBox,这些 getBBox 坐标与屏幕像素不再相同.有没有函数或方法来获取考虑当前 viewBox 和 svg 元素的像素大小的坐标?

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?

推荐答案

Demo: 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;
}

洋红色方块是 HTML 元素中绝对定位的 div,使用屏幕空间坐标.当您拖动矩形或调整矩形的大小时,将调用此函数并将角 div 移动到四个角上(第 116-126 行).请注意,即使矩形处于任意嵌套转换(例如蓝色矩形)并且 SVG 已缩放(调整浏览器窗口的大小),这也有效.

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).

为了好玩,将其中一个矩形拖离 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.

这篇关于获取 Rect 元素的屏幕像素坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆