Key Points
viewBox
attribute, and can be scaled to any size. This complicates adding SVG elements according to cursor position, especially in responsive designs. getBoundingClientRect()
method. However, the conversion from SVG to DOM coordinates is more challenging and requires the use of SVG's own matrix decomposition mechanism. .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>
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 conversionSVG 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>
circle { stroke-width: 5; stroke: #f00; fill: #ff0; } circle:hover { stroke: #090; fill: #fff; }
const mycircle = document.getElementById('mycircle'); mycircle.addEventListener('click', (e) => { console.log('circle clicked - enlarging'); mycircle.setAttribute('r', 60); });
SVG to DOM coordinate conversion
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 .right
minus .left
) .height
: The height of the element (not supported in IE8 and below, but the same as .bottom
minus .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
.
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! …
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>
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>
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; }
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.
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>
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>
(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()
FAQs about DOM to SVG coordinates and reverse conversion
attribute, which can be scaled and transformed. viewBox
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
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
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
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.
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.
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.
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.
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.
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!