SVGPoint DOM Interface Mathematical Operations
The SVGPoint interface represents a 2D or 3D coordinate
point within the Scalable Vector Graphics (SVG) Document Object Model.
This article explains the native and manual mathematical operations that
can be performed using SVGPoint, focusing on native matrix
transformations, coordinate system conversions, and standard vector
arithmetic.
Native Matrix Transformation
The primary built-in mathematical method provided by the
SVGPoint interface is matrixTransform(). This
method multiplies the point’s coordinates by a 2×3 transformation matrix
(an SVGMatrix or DOMMatrix), returning a new
SVGPoint object representing the transformed location.
Mathematically, the transformation performs an affine matrix multiplication:
\[ \begin{bmatrix} x' \\ y' \\ 1 \end{bmatrix} = \begin{bmatrix} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ 1 \end{bmatrix} = \begin{bmatrix} ax + cy + e \\ bx + dy + f \\ 1 \end{bmatrix} \]
Through matrixTransform(), you can execute the following
geometric operations:
- Translation: Shifts a point along the X and Y axes using offset values in the matrix (\(e\) and \(f\)).
- Scaling: Multiplies coordinates by horizontal and vertical scale factors (\(a\) and \(d\)).
- Rotation: Rotates a point around the origin using trigonometric values (\(\cos\theta\), \(\sin\theta\), \(-\sin\theta\), \(\cos\theta\)).
- Skewing (Shearing): Distorts coordinates along the X or Y axis based on tangent angles (\(c = \tan\alpha\), \(b = \tan\beta\)).
Coordinate System Inversion and Mapping
By combining matrixTransform() with the inverse of the
Current Transformation Matrix (getScreenCTM().inverse()),
you can perform coordinate projection. This mathematical operation
converts screen coordinates (such as mouse or touch events) into SVG
user space coordinates.
const svg = document.querySelector("svg");
const point = svg.createSVGPoint();
point.x = event.clientX;
point.y = event.clientY;
const svgCoordinates = point.matrixTransform(svg.getScreenCTM().inverse());Component-Wise Vector Arithmetic
While matrixTransform() is the only built-in
transformation method on the interface, the mutable x and
y properties of SVGPoint enable manual
component-wise vector mathematics:
- Vector Addition and Subtraction: Offsetting one point by another (\(P_3.x = P_1.x \pm P_2.x\), \(P_3.y = P_1.y \pm P_2.y\)).
- Scalar Multiplication and Division: Scaling vector lengths directly (\(P.x = P.x \times s\), \(P.y = P.y \times s\)).
- Euclidean Distance Calculation: Determining the
distance between two
SVGPointobjects using the Pythagorean theorem: \(d = \sqrt{(P_2.x - P_1.x)^2 + (P_2.y - P_1.y)^2}\). - Magnitude and Normalization: Finding vector length (\(\|v\| = \sqrt{x^2 + y^2}\)) and computing unit vectors by dividing coordinates by the magnitude.
- Dot Product: Calculating directional alignment and projecting vectors (\(v_1 \cdot v_2 = x_1 x_2 + y_1 y_2\)).