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

FabricJS – 如何將 Line 物件水平居中在畫布的目前視窗上?

WBOY
發布: 2023-09-01 13:41:02
轉載
1336 人瀏覽過

FabricJS – 如何将 Line 对象水平居中在画布的当前视口上?

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

文法

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

Line 物件的預設外觀

範例

讓我們來看一個程式碼範例,看看不使用 viewportCenterH 方法時 Line 物件的外觀。在這種情況下,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 horizontally 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: 6,
      });
      
      // Add it to the canvas
      canvas.add(line);
   </script>
</body>
</html>
登入後複製

使用viewportCenterH方法

範例

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

<!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 viewportCenterH method</h2>
   <p>
      You can see that the line object is centered horizontally 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: 6,
      });
   
      // Add it to the canvas
      canvas.add(line);
      
      // Using the viewportCenterH method
      line.viewportCenterH();
   </script>
</body>
</html>
登入後複製

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

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