本文内容转自

Why we need Coordinate Translation

This is the tricky part. Presume you click an SVG and want to create or position an SVG element at that point. The event handler object will give you the DOM .clientX and .clientY pixel coordinates but these must be translated to SVG units.

It’s tempting to think you can calculate the x and y coordinates of an SVG point by applying a multiplication factor to the pixel location. For example, if a 1000 unit-width SVG is placed in a 500px width container, you can multiply any cursor x coordinate by two to get the SVG location. It rarely works!…

  • There is no guarantee the SVG will fit exactly into your container.
  • If the page or element dimensions change – perhaps in response to the user resizing the browser – the x and y factors must be re-calculated.
  • The SVG could be transformed in either 2D or 3D space.
  • Even if you overcome these hurdles, it never quite works as you expect. There’s often a margin of error.

DOM to SVG Coordinate Translation

Fortunately, SVGs provide their own matrix factoring mechanisms to translate coordinates. The first step is to create a point on the SVG using the createSVGPoint() method and pass in our screen x and y coordinates:

var svg = document.getElementById('mysvg'),
pt = svg.createSVGPoint();

pt.x = 100;
pt.y = 200;

We can then apply a matrix transformation. That matrix is created from an inverse of the SVG’s (under-documented!) getScreenCTM() method which maps SVG units to screen coordinates:

var svgP = pt.matrixTransform(svg.getScreenCTM().inverse());

svgP now has .x and .y properties which provide the SVG coordinate location.

SVG to DOM Coordinate Translation

Element.getBoundingClientRect() is supported in all browsers and returns an DOMrect object with the following properties in pixel dimensions:

  • .x and .left – x-coordinate, relative to the viewport origin, of the left side of the element
  • .right – x-coordinate, relative to the viewport origin, of the right side of the element
  • .y and .top – y-coordinate, relative to the viewport origin, of the top side of the element
  • .bottom – y-coordinate, relative to the viewport origin, of the bottom side of the element
  • .width – width of the element (not supported in IE8 and below but is identical to .right minus .left)
  • .height – height of the element (not supported in IE8 and below but is identical to .bottom minus .top)

All coordinates are relative to the browser viewport and will therefore change as the page is scrolled. The absolute location on the page can be calculated by adding window.scrollX to .left and window.scrollY to .top.

posted on 2019-11-10 15:15  MnCu  阅读(488)  评论(0编辑  收藏  举报