Getting the Screen Pixel coordinates of a Rect element

前端 未结 2 1556
无人共我
无人共我 2020-12-05 03:28

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 posit

相关标签:
2条回答
  • 2020-12-05 03:46

    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.

    0 讨论(0)
  • 2020-12-05 04:06

    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.

    See the files here, which include a fallback implementation of getScreenBBox that should work in all browsers.

    0 讨论(0)
提交回复
热议问题