zoom svg with transformmatrix in javascript

To zoom an SVG using a transform matrix in JavaScript, you can follow these steps -

  1. Get the SVG element -
index.tsx
const svg = document.getElementById("svgElement");
51 chars
2 lines
  1. Create a new matrix and scale it by the desired factor. Here, we will use a scale factor of 2 for zooming in, and 0.5 for zooming out -
index.tsx
const matrix = svg.createSVGMatrix();
const scaleFactor = 2; //Change this value to zoom in/out as per your requirement
const scaledMatrix = matrix.scale(scaleFactor);
168 chars
4 lines
  1. Apply the new matrix as a transform on the SVG element -
index.tsx
svg.transform.baseVal.initialize(scaledMatrix);
48 chars
2 lines

Here's the complete implementation for zooming in and out using a mouse wheel event -

index.tsx
const svg = document.getElementById("svgElement");

svg.addEventListener("wheel", function(e) {
  e.preventDefault();

  const matrix = svg.createSVGMatrix();
  const scaleFactor = e.deltaY > 0 ? 0.5 : 2;
  const point = svg.createSVGPoint();
  
  point.x = e.offsetX;
  point.y = e.offsetY;

  const scaledMatrix = matrix.translate(point.x, point.y).scale(scaleFactor).translate(-point.x, -point.y);
  svg.transform.baseVal.initialize(scaledMatrix);
});
455 chars
16 lines

Note that we are translating the matrix to the mouse position, scaling it, and then translating it back to keep the zoom centered on the mouse position.

gistlibby LogSnag