Home > Web Front-end > CSS Tutorial > How to Translate from DOM to SVG Coordinates and Back Again

How to Translate from DOM to SVG Coordinates and Back Again

Joseph Gordon-Levitt
Release: 2025-02-10 10:05:12
Original
373 people have browsed it

How to Translate from DOM to SVG Coordinates and Back Again

Key Points

  • SVG has its own coordinate system defined based on the viewBox attribute, and can be scaled to any size. This complicates adding SVG elements according to cursor position, especially in responsive designs.
  • SVG embedded in HTML pages becomes part of the DOM and can be operated like other elements. This allows the conversion between coordinate systems to be completely avoided.
  • The conversion from DOM to SVG coordinates can be achieved by extracting the position and size by the getBoundingClientRect() method. However, the conversion from SVG to DOM coordinates is more challenging and requires the use of SVG's own matrix decomposition mechanism.
  • SVG or individual elements can be transformed by translation, scaling, rotation, and/or tilting, which affects the final SVG coordinates. The .getScreenCTM() method can be applied to any element as well as the SVG itself to take into account all transformations.

Using SVG is relatively simple - until you want to mix DOM and vector interactions.

SVGs defines its own coordinate system in its viewBox attribute. For example:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600"></svg>
Copy after login
Copy after login
Copy after login

This sets 800 unit width and 600 unit height starting from 0,0. These units are any units of measurement used for drawing, and the decimal part of the unit can be used. If you place this SVG in an area of ​​800 x 600 pixels, each SVG unit should be mapped directly to one screen pixel.

However, vector images can be scaled to any size – especially in responsive designs. Your SVG can be scaled down to 400 x 300, and can even stretch deformation in 10 x 1000 space. If you want to place them according to the cursor position, it becomes more difficult to add more elements to this SVG.

Note: For more information on SVG coordinates, see the Sara Soueidan's viewport, viewBox, and preserveAspectRatio articles.

Avoid coordinate conversion

You may be able to avoid the conversion between coordinate systems altogether.

SVG embedded in HTML pages (rather than images or CSS backgrounds) becomes part of the DOM and can be operated like other elements. For example, a basic SVG containing a single circle:

<svg id="mysvg" xmlns="https://www.w3.org/2000/svg" viewBox="0 0 800 600" preserveAspectRatio="xMidYMid meet">
  <circle id="mycircle" cx="400" cy="300" r="50" />
</svg>
Copy after login
Copy after login
Copy after login
You can apply CSS effects to it:

circle {
  stroke-width: 5;
  stroke: #f00;
  fill: #ff0;
}

circle:hover {
  stroke: #090;
  fill: #fff;
}
Copy after login
Copy after login
You can also attach event handlers to modify properties:

const mycircle = document.getElementById('mycircle');

mycircle.addEventListener('click', (e) => {
  console.log('circle clicked - enlarging');
  mycircle.setAttribute('r', 60);
});
Copy after login
The following example adds thirty random circles to an SVG image, applies a hover effect in CSS, and increases the radius by ten units using JavaScript when clicking the circle.

View the example on CodePen

SVG to DOM coordinate conversion

It may be necessary to overlay the DOM element over the SVG element—for example, display a menu or information box on the active country displayed on the world map. Assuming that SVG is embedded in HTML, the elements become part of the DOM, so the position and size can be extracted using the

method. (Open the console in the example above to show the new properties of clicking the circle after the radius increases.) getBoundingClientRect()

Element.getBoundingClientRect() is supported in all browsers and returns a DOMRect object with the following pixel size attributes:

  • .x and .left: x-coordinate on the left side of the element relative to the viewport origin
  • .right: x-coordinate on the right side of the element relative to the viewport origin
  • .y and .top: The y-coordinate of the top of the element relative to the viewport origin
  • .bottom: The y-coordinate of the bottom of the element relative to the viewport origin
  • .width: The width of the element (not supported in IE8 and below, but the same as .rightminus .left)
  • .height: The height of the element (not supported in IE8 and below, but the same as .bottomminus .top)

All coordinates are relative to the browser viewport, so they change as the page scrolls. The absolute position on the page can be calculated by adding window.scrollX to .left and window.scrollY to .top.

DOM to SVG coordinate conversion

This is more challenging. Suppose you want to place the new SVG element on its viewBox where the click event occurred. The event handler object provides DOM .clientX and .clientY pixel coordinates, but must be converted to SVG units.

You might think that you can calculate the coordinates of SVG points by applying multiplication factors. For example, if an SVG of 1000 unit width is placed in a container of 500 pixels wide, you can multiply any DOM x coordinates by 2 to get the SVG position. This won't work! …

  • The SVG is not guaranteed to be perfect for your container.
  • If the element size changes—perhaps resizes the browser in response to the user—the width and height factors must be recalculated.
  • SVG or one or more elements can be transformed in 2D or 3D space.
  • Even if you overcome these obstacles, it never works as you expected and there are often errors.

Luckily, SVG provides its own matrix decomposition mechanism to convert coordinates. The first step is to create a point on the SVG using the createSVGPoint() method and pass the screen/event x and y coordinates into:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600"></svg>
Copy after login
Copy after login
Copy after login

You can then apply a matrix transformation created from the inverse matrix of the SVG's .getScreenCTM() method, which maps SVG units to screen coordinates:

<svg id="mysvg" xmlns="https://www.w3.org/2000/svg" viewBox="0 0 800 600" preserveAspectRatio="xMidYMid meet">
  <circle id="mycircle" cx="400" cy="300" r="50" />
</svg>
Copy after login
Copy after login
Copy after login

svgP now has .x and .y properties, which provide coordinates on the SVG viewBox.

The following code places the circle at the point clicked on the SVG canvas:

circle {
  stroke-width: 5;
  stroke: #f00;
  fill: #ff0;
}

circle:hover {
  stroke: #090;
  fill: #fff;
}
Copy after login
Copy after login

Note: The createElementNS() method is the same as the standard DOM createElement() method, except that it specifies an XML namespace URI. In other words, it works on SVG documents rather than HTML.

Convert to transform SVG coordinates

There is another more complex aspect. An SVG or a single element can be transformed by translation, scaling, rotation, and/or tilting, which affects the final SVG coordinates. For example, the following <g> layer is 4 times larger than the standard SVG unit, so the coordinates will be one quarter of the SVG coordinates:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600"></svg>
Copy after login
Copy after login
Copy after login

The generated rectangle looks like has a width and height of 400 units at positions 200, 200.

Luckily, the

method can be applied to any element as well as the SVG itself. The generated matrix takes into account all transformations, so you can create a simple .getScreenCTM() conversion function: svgPoint()

<svg id="mysvg" xmlns="https://www.w3.org/2000/svg" viewBox="0 0 800 600" preserveAspectRatio="xMidYMid meet">
  <circle id="mycircle" cx="400" cy="300" r="50" />
</svg>
Copy after login
Copy after login
Copy after login
The following demonstration works in all modern browsers,

(If you convert JavaScript to ES5, it works in IE11 too!) . When clicking/clicking on SVG, a circle is added to the cursor point.

This also happens when clicking on the transformed

area, but passing the element instead of the SVG itself to the <g> function to ensure the correct coordinates are calculated: svgPoint()

View the example on CodePen

Ideally, it is best to avoid DOM to/from SVG coordinate conversion, but when this is not possible, use the method described above to ensure that the process is robust at all page sizes.

FAQs about DOM to SVG coordinates and reverse conversion

What is the difference between DOM and SVG coordinates?

Document Object Model (DOM) and Scalable Vector Graphics (SVG) are both components of web development, but they have different uses. DOM is the programming interface for HTML and XML documents. It represents the structure of a document and provides a way to manipulate its content and visual representation. On the other hand, SVG is an XML-based vector image format for two-dimensional graphics. The main difference between the two is their coordinate system. DOM uses a pixel-based coordinate system, while SVG uses a system based on the

attribute, which can be scaled and transformed. viewBox

How to convert DOM coordinates to SVG coordinates?

Converting DOM coordinates to SVG coordinates involves creating a point in the SVG coordinate system using the

method of the SVG element. You can then use the createSVGPoint method to convert the point to an SVG coordinate system. This method takes a DOMMatrix object, which represents the transformation matrix of the SVG element. matrixTransform

How to convert SVG coordinates back to DOM coordinates?

To convert SVG coordinates back to DOM coordinates, you can use the

method of the SVGMatrix object. This method returns a new SVGMatrix object, which is the inverse matrix of the original matrix. By multiplying the SVG points by this inverse matrix, you can convert it back to the DOM coordinate system. inverse

What is the role of the viewBox attribute in SVG?

The

attribute in

in SVG is used to specify the aspect ratio and coordinate system of the SVG image. It allows you to control the scaling and positioning of SVG elements. The viewBox attribute takes four values: min-x, min-y, width, and height. These values ​​define the rectangle in the SVG coordinate system. viewBox

How to use DOM to SVG package in my project?

DOM to SVG package is a useful tool for converting DOM coordinates to SVG coordinates and reverse conversion. To use it in your project, you need to install it using npm (the package manager for the JavaScript programming language). Once installed, you can introduce it in your JavaScript file and perform the conversion using its methods.

What is the cx attribute in SVG?

The

attribute in cx in SVG is used to specify the x-coordinate of the center of the circle. It is one of the basic properties for creating an SVG circle. The value of the cx attribute is the length in the user coordinate system.

Can I use both DOM and SVG in my webpage?

Yes, you can use both DOM and SVG in your web page. SVG is embedded in HTML, so it is part of the DOM. You can use DOM methods and properties to manipulate SVG elements. This enables you to create dynamic and interactive graphics on your web pages.

How is the coordinate system in SVG different from that in HTML?

The coordinate system in SVG is different from that in HTML. In HTML, the coordinate system is pixel-based and the origin is in the upper left corner of the page. In SVG, the coordinate system is defined by the viewBox attribute, and the origin is in the upper left corner of viewBox. This makes the SVG graphics scalable and independent of resolution.

How to convert SVG coordinates?

You can use the transform attribute to convert SVG coordinates. This property allows you to apply various transformations to SVG elements, such as translation, rotation, scaling, and tilting. The value of the transform attribute is a list of transform functions, each function is applied to the elements in the order listed.

What are some common use cases for converting between DOM and SVG coordinates?

In many cases, it is very useful to convert between DOM and SVG coordinates. For example, if you are creating an interactive SVG graph, you may need to convert mouse coordinates (located in the DOM coordinate system) to SVG coordinates to manipulate the SVG element. Instead, if you are creating a custom SVG element, you may need to convert its coordinates back to the DOM coordinate system to place it correctly on the page.

The above is the detailed content of How to Translate from DOM to SVG Coordinates and Back Again. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template