Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
SVG zoom-in and zoom-out in React JS
In this article, we will see how to zoom SVG images in React JS. It is really useful in some cases. We will use the react-svg-pan-zoom package to create a feature that will zoom-in or rotate our SVG image.
First create a React project −
npx create-react-app tutorialpurpose
Go to the project directory −
cd tutorialpurpose
Example
Install the react-svg-pan-zoom package −
npm i --save react-svg-pan-zoom
This package will allow us to implement an area over which we can zoom-in and zoom-out and even rotate an image.
Add the following lines of code in App.js −
import React, { useRef, useEffect } from "react";
import { UncontrolledReactSVGPanZoom } from "react-svg-panzoom";
export default function App() {
const Viewer = useRef(null);
useEffect(() => {
Viewer.current.fitToViewer();
}, []);
const _zoomOnViewerCenter = () =>
Viewer.current.zoomOnViewerCenter(1.1);
const _fitSelection = () => Viewer.current.fitSelection(40,40, 200, 200);
const _fitToViewer = () => Viewer.current.fitToViewer();
return (
<div>
<h1>UncontrolledReactSVGPanZoom</h1>
<hr />
<button className="btn" onClick={() =>_zoomOnViewerCenter()}>Zoom on center
</button>
<button className="btn" onClick={() =>_fitSelection()}> Zoom area 200x200
</button>
<button className="btn" onClick={() => _fitToViewer()}> Fit
</button>
<hr />
<UncontrolledReactSVGPanZoom ref={Viewer} width={500} height={500}>
<svg width={617} height={316}>
<g fillOpacity=".5" strokeWidth="4">
<rectx="400"
y="40"
width="100"
height="200"
fill="#4286f4"
stroke="#f4f142"
/>
</g>
</svg>
</UncontrolledReactSVGPanZoom>
</div>
);
}
Explanation
This is the default code from the documentation.
We first created a reference, where we referenced its default view, which will fit to the screen.
Then we created 3 functions to change the zoom settings.
In
we give reference and inside it, we add an SVG image to operate.
Output
On execution, it will produce the following output −
