首頁 > web前端 > js教程 > 主體

FabricJS – 如何將 Line 物件置於畫布目前視窗的中心?

王林
發布: 2023-08-24 22:41:05
轉載
689 人瀏覽過

FabricJS – 如何将 Line 对象置于画布当前视口的中心?

在本教程中,我們將學習如何使用 FabricJS 將 Line 物件在畫布的當前視窗中水平和垂直居中。 Line 元素是 FabricJS 中提供的基本元素之一。它用於創建直線。由於線元素在幾何上是一維的並且不包含內部,因此它們永遠不會被填充。我們可以透過建立 Fabric.Line 的實例、指定線的 x 和 y 座標並將其新增至畫布來建立線物件。為了讓 Line 物件在畫布的目前視窗上居中,我們使用 viewportCenter 方法。

語法

 viewportCenter(): fabric.Object 
登入後複製

Line 物件的預設外觀

範例

讓我們看一個程式碼範例,看看不使用viewportCenter方法時Line 物件的外觀。在這種情況下,線條物件將不會在畫布上居中。

<!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>Default appearance of the Line object</h2>
   <p>
      You can see that the line object is not centered with respect to the current viewport of canvas
   </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 Line object
      var line = new fabric.Line([200, 100, 100, 40], {
         stroke: "blue",
         strokeWidth: 20,
      });
      
      // Add it to the canvas
      canvas.add(line);
   </script>
</body>
</html>
登入後複製

使用viewportCenter方法

範例

讓我們來看一個程式碼範例,看看使用 viewportCenter 方法時線條物件的樣子。在這種情況下,我們的線條物件將相對於畫布的當前視窗居中。

<!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 viewportCenter method</h2>
   <p>
      You can see that the line object is centered with respect to the current viewport of canvas 
   </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 Line object
      var line = new fabric.Line([200, 100, 100, 40], {
         stroke: "blue",
         strokeWidth: 20,
      });
      
      // Add it to the canvas
      canvas.add(line);
      
      // Using the viewportCenter method
      line.viewportCenter();
   </script>
</body>
</html>
登入後複製

以上是FabricJS – 如何將 Line 物件置於畫布目前視窗的中心?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!