Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

javascript - Getting the Screen Pixel coordinates of a Rect element

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...