React JS 中 SVG 縮放和縮小


在本篇文章中,我們將瞭解如何在 React JS 中縮放 SVG 影像。在某些情況下它非常有用。我們將使用 react-svg-pan-zoom 包建立一個功能,用於放大或旋轉我們的 SVG 影像。

首先建立 React 專案 −

npx create-react-app tutorialpurpose

轉到專案目錄 −

cd tutorialpurpose

示例

安裝 react-svg-pan-zoom 包 −

npm i --save react-svg-pan-zoom

此包將允許我們在可以放大和縮小、甚至旋轉影像的區域上進行實現。

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>
   );
}

說明

這是文件中的預設程式碼。

  • 我們首先建立了一個引用,引用了適合顯示螢幕的預設檢視。

  • 然後我們建立了 3 個函式來更改縮放設定。

  • 在 <UncontrolledReactSVGPanZoom> 中,我們提供了引用,並在其中新增 SVG 影像來進行操作。

輸出

執行後,它將生成以下輸出 −

更新於: 2021-09-29

2000+ 瀏覽

開啟你的 事業

完成課程,獲取認證

開始學習
廣告
© . All rights reserved.