如何在 FabricJS 中獲取包含折線物件的畫布的縮放級別?


我們可以透過建立fabric.Polyline的例項來建立一個折線物件。折線物件可以由一組連線的直線段來表徵。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性來輕鬆自定義它。

為了找到當前的縮放級別,我們使用getZoom()方法。此方法返回一個表示縮放級別的數字

語法

getZoom(): Number

示例 1:使用 getZoom() 方法

讓我們看一個程式碼示例,說明如何使用getZoom()方法查詢包含折線物件的畫布的縮放級別。我們將把該值記錄到控制檯中。對於此示例,我們將記錄預設值 1。

<!DOCTYPE html>
<html>
<head>
   <!-- Adding the Fabric JS Library-->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>
<body>
   <h2>Using the getZoom() method</h2>
   <p> You can open Console from Dev tools and see the zoom level </p>
   <canvas id="canvas"></canvas>
   <script>
      
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
      
      // Initiate a polyline instance
      var polyline = new fabric.Polyline(
         [
            { x: 500, y: 20 },
            { x: 550, y: 60 },
            { x: 550, y: 200 },
            { x: 350, y: 200 },
            { x: 350, y: 60 },
         ],
         {
            fill: "white",
            stroke: "blue",
            strokeWidth: 2,
         }
      );
      
      // Add it to the canvas
      canvas.add(polyline);
      
      // Using getZoom() method
      var zoomLevel = canvas.getZoom();
      console.log("Zoom Level: ", zoomLevel);
   </script>
</body>
</html>

示例 2:使用 getZoom() 方法和縮放的折線

讓我們看一個程式碼示例,在這個示例中,我們將使用setZoom()設定縮放,然後使用getZoom()方法獲取新的縮放值。我們傳遞值1.3,這將放大,並在輸出中可見,該值也會在控制檯中顯示為1.3

<!DOCTYPE html>
<html>
<head>
   <!-- Adding the Fabric JS Library-->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>
<body> 
   <h2>Using the getZoom() method and with a zoomed in polyline</h2>
   <p> You can open Console from Dev tools and see the zoom level </p>
   <canvas id="canvas"></canvas>
   <script>
      
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
      
      // Initiate a polyline instance
      var polyline = new fabric.Polyline(
         [
            { x: 500, y: 20 },
            { x: 550, y: 60 },
            { x: 550, y: 200 },
            { x: 350, y: 200 },
            { x: 350, y: 60 },
         ],
         {
            fill: "white",
            stroke: "blue",
            strokeWidth: 2,
         }
      );
      
      // Add it to the canvas
      canvas.add(polyline);
      
      // Set the zoom level
      canvas.setZoom(1.3);
      
      // Using getZoom() method
      var zoomLevel = canvas.getZoom();
      console.log("Zoom Level: ", zoomLevel);
   </script>
</body>
</html>

更新於:2023年2月16日

492 次瀏覽

啟動您的職業生涯

完成課程獲得認證

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