Guide to the SVG createSVGPoint Method
The createSVGPoint method on the root SVG DOM element
(<svg>) is an interface utility used to instantiate a
new, unattached SVGPoint object representing a 2D
coordinate point \((x, y)\). This
article explains the purpose of createSVGPoint, its
critical role in converting screen coordinates to SVG coordinate
systems, and how it functions in JavaScript applications.
Purpose of createSVGPoint
When interacting with an <svg> element, standard
DOM mouse and touch events provide coordinates relative to the browser
viewport (clientX, clientY). However, an SVG
canvas typically has its own internal coordinate system defined by
attributes such as viewBox, transform,
scaling, and responsive sizing.
The createSVGPoint() method generates an
SVGPoint object initialized at \((0, 0)\). This point object serves as a
data structure specifically designed to interact with SVG transformation
matrices, allowing developers to map external screen coordinates
accurately into the SVG’s internal user coordinate space.
How Coordinate Conversion Works
To translate a user interaction (like a mouse click) into the exact
coordinate within an SVG drawing, createSVGPoint is used in
tandem with the SVG’s Current Transformation Matrix (CTM).
- Create the Point: Call
svg.createSVGPoint()to initialize the coordinate container. - Assign Screen Coordinates: Set the point’s
xandyproperties to match event coordinates (e.g.,event.clientX,event.clientY). - Get the Inverse Matrix: Retrieve the screen
transformation matrix using
svg.getScreenCTM()and invert it with.inverse(). - Apply the Transformation: Use
point.matrixTransform(inverseCTM)to calculate the precise \((x, y)\) coordinates inside the SVG’s local coordinate space.
const svg = document.querySelector('svg');
const point = svg.createSVGPoint();
svg.addEventListener('click', (event) => {
point.x = event.clientX;
point.y = event.clientY;
const svgCoords = point.matrixTransform(svg.getScreenCTM().inverse());
console.log(`SVG X: ${svgCoords.x}, SVG Y: ${svgCoords.y}`);
});Key Characteristics
- Decoupled Lifecycle: The point returned by
createSVGPoint()is not rendered directly to the screen; it is purely a mathematical utility. - Matrix Operations: The resulting object includes
the
matrixTransform()method, which performs matrix multiplication against any validSVGMatrix. - Standard Evolution: While
createSVGPoint()andSVGPointare legacy parts of the SVG 1.1 specification, they remain universally supported across all modern browsers. In modern specifications (Geometry Interfaces Module),SVGPointaliases the newerDOMPointinterface.