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

问题描述

我试图通过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 thecoordinates 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元素的Screen Pixel坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 01:47