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).

  1. Create the Point: Call svg.createSVGPoint() to initialize the coordinate container.
  2. Assign Screen Coordinates: Set the point’s x and y properties to match event coordinates (e.g., event.clientX, event.clientY).
  3. Get the Inverse Matrix: Retrieve the screen transformation matrix using svg.getScreenCTM() and invert it with .inverse().
  4. 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