For more tips like this, sign up to the weekly newsletter!
Use SVG viewBox for easy zooming
The <svg>
element has an attribute called viewBox
. It defines the origin point (where x = 0 and y = 0) and the width/height of the viewport. It is usually set to 0 0
and the dimensions of the image inside the <svg>
.
Use viewBox
for zooming
But you can also use it to zoom. For example, for an image with dimensions of 630 x 630, the full image is shown if viewBox
is 0 0 630 630
. To zoom to the bottom right, use 315 315 315 315
(the top-left point is the middle of the image, and the width/height is half the original).
For a simple zoom-to-hover effect, you can use something like this:
const svgElement = ... // Get the SVG element
const [,,originalWidth, originalHeight] = svgElement.getAttribute("viewBox").split(" ").map(Number);
svgElement.addEventListener("mousemove", (event) => {
const {top, left, width, height} = svgElement.getBoundingClientRect();
const eventTop = event.clientY - top;
const eventLeft = event.clientX - left;
svgElement.setAttribute("viewBox", `${eventLeft / width * originalWidth - originalWidth / 4} ${eventTop / height * originalHeight - originalHeight / 4} ${originalWidth / 2} ${originalHeight / 2}`)
});
svgElement.addEventListener("mouseout", () => {
svgElement.setAttribute("viewBox", `0 0 ${originalWidth} ${originalHeight}`);
});