Translating Viewport Coordinates Into Element Local Coordinates Using Element.getBoundingClientRect() Преобразование координат области просмотра в локальные координаты элемента с помощью Element.getBoundingClientRect - gitbbln/gitbbln.github.io GitHub Wiki

Some user interaction events provide positional meta-data about the event in relation to the browser's viewport. For example, if you highlight text, the Selection API reports the bounding box of the selected Ranges in relation to the viewport. In order for your application to react to such events, it's not uncommon to have to translate the reported viewport coordinates into element-local coordinates to render subsequent user interface components. To do this, we can use the Element.getBoundingClientRect() method and some simple math.

Некоторые события взаимодействия с пользователем предоставляют позиционные метаданные о событии относительно области просмотра браузера. Например, если вы выделяете текст, API выбора сообщает ограничивающую рамку выбранных диапазонов относительно области просмотра. Чтобы ваше приложение реагировало на такие события, нередко приходится переводить сообщаемые координаты области просмотра в локальные координаты элемента для визуализации последующих компонентов пользовательского интерфейса. Для этого мы можем использовать метод Element.getBoundingClientRect () и некоторую простую математику.

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>
		Translating Viewport Coordinates To Element-Local Coordinates Using .getBoundingClientRect()
	</title>
 
	<link rel="stylesheet" type="text/css" href="./demo.css" />
</head>
<body>
 
	<h1>
		Translating Viewport Coordinates To Element-Local Coordinates Using .getBoundingClientRect()
	</h1>
 
	<div class="box box-a"></div>
	<div class="box box-b"></div>
	<div class="box box-c"></div>
	<div class="box box-d"></div>
	<div class="box box-e"></div>
	<div class="box box-f"></div>
 
	<script type="text/javascript">
 
		document.addEventListener( "click", handleClick, false );
 
		function handleClick( event ) {
 
			if ( ! event.target.classList.contains( "box" ) ) {
 
				return;
 
			}
 
			// Get the VIEWPORT-relative coordinates of the click.
			// --
			// NOTE: The MouseEvent interface has a bunch of coordinate-related values,
			// including offsetX and offsetY which may seem relevant to this demo. But,
			// this demo is NOT about the MouseEvent - it's about coordinate translation.
			// It's only coincidental that I'm using mouse events to drive it.
			var viewportX = event.clientX;
			var viewportY = event.clientY;
 
			// Now that we have the VIEWPORT coordinates of the CLICK, we need to get the
			// VIEWPORT position of the target element. This will give us coordinates
			// that are operating in the same grid system. Luckily, that's exactly what
			// the .getBoundingClientRect() method gives us!!
			var boxRectangle = event.target.getBoundingClientRect();
 
			// Now that we have the targets VIEWPORT coordinates and the click's VIEWPORT
			// coordinates, we can take the difference between the two in order to
			// translate the VIEWPORT coordinates into target-LOCAL coordinates.
			var localX = ( viewportX - boxRectangle.left );
			var localY = ( viewportY - boxRectangle.top );
 
			// In this particular demo, we have to take into account the border of the
			// box element since the .getBoundingClientRect() values will be relative to
			// the outer-most boundary of the box.
			var borderWidth = parseInt( window.getComputedStyle( event.target ).borderTopWidth, 10 );
			localX -= borderWidth;
			localY -= borderWidth;
 
			// Now that we have the target-LOCAL coordinates, let's append a DOT element
			// to the target container for proof of purchase.
			var point = document.createElement( "div" );
			point.classList.add( "point" );
			point.style.left = ( localX + "px" );
			point.style.top = ( localY + "px" );
			event.target.appendChild( point );
 
			console.log(
				"Translating Viewport {", viewportX, ",", viewportY, "}",
				"to Local {", localX, ",", localY, "}"
			);
 
		}
 
	</script>
 
</body>
</html>

Run this demo in JavaScript Demos project on GitHub.

View this code in my JavaScript Demos project on GitHub.

The Element.getBoundingClientRect() method reports the size and position of the contextual element relative to the browser's viewport. If we have other positional information that is also relative to the browser's viewport, we can calculate the element-local position by taking the difference between the two viewport-relative positions:

Метод Element.getBoundingClientRect () сообщает размер и положение контекстного элемента относительно области просмотра браузера. Если у нас есть другая позиционная информация, которая также относится к области просмотра браузера, мы можем вычислить локальную позицию элемента, взяв разницу между двумя позициями относительно области просмотра:

To see this in action, I've put together a simple demo that tracks mouse-clicks on the document (via event-delegation). It then takes the mouse-click viewport-coordinates and uses .getBoundingClientRect() to calculate the position of the click within a target element. The calculated Element-local position is then used to render a "dot" under the user's mouse As you can see, we're using event-delegation on the Document to listen for mouse-click events. We're then taking clicks that originate from within one of the boxes, and using the viewport-delta of the mouse coordinates and the box's bounding rectangle in order to append and position a "dot" element. And, when we run this code and click in one of the boxes, we get the following browser output:

Чтобы увидеть это в действии, я собрал простую демонстрацию, которая отслеживает щелчки мышью по документу (через делегирование событий). Затем он принимает координаты окна просмотра щелчка мыши и использует .getBoundingClientRect () для вычисления позиции щелчка в целевом элементе. Вычисленное локальное для элемента положение затем используется для визуализации «точки» под мышью пользователя. Как вы можете видеть, мы используем делегирование событий в документе для прослушивания событий щелчка мышью. Затем мы выполняем щелчки, происходящие из одного из блоков, и используем дельту окна просмотра координат мыши и ограничивающий прямоугольник блока, чтобы добавить и разместить «точечный» элемент. И, когда мы запускаем этот код и щелкаем в одном из полей, мы получаем следующий вывод браузера:

The Element.getBoundingClientRect() method is an awesome feature that has standardized support in all major browsers, going back to IE9. In this case, you can see how easy it makes it to translate viewport-relative coordinates into element-local coordinates.

Метод Element.getBoundingClientRect () сообщает размер и положение контекстного элемента относительно области просмотра браузера. Если у нас есть другая позиционная информация, которая также относится к области просмотра браузера, мы можем вычислить локальную позицию элемента, взяв разницу между двумя позициями относительно области просмотра:

⚠️ **GitHub.com Fallback** ⚠️