如何使用 FabricJS 鎖定線條的水平移動?


在本教程中,我們將學習如何使用 FabricJS 鎖定線條的水平移動。線條元素是 FabricJS 提供的基本元素之一。它用於建立直線。由於線條元素在幾何上是一維的並且不包含內部,因此它們永遠不會填充。我們可以透過建立 fabric.Line 的例項,指定線條的 x 和 y 座標並將其新增到畫布上來建立線條物件。我們還可以指定是否希望線條物件僅在 Y 軸上移動。這可以透過使用 lockMovementX 屬性來實現。

語法

new fabric.Line(points: Array, { lockMovementX: Boolean }: Object)

引數

  • points − 此引數接受一個陣列,該陣列確定 (x1, y1) 和 (x2, y2) 值,分別為線條起點和終點的 x 軸和 y 軸座標。

  • options (可選) − 此引數是一個物件,它為我們的線條物件提供額外的自定義功能。使用此引數,可以更改與物件相關的原點、筆劃寬度和許多其他屬性,其中lockMovementX 是一個屬性。

選項鍵

  • lockMovementX − 此屬性接受一個布林值。如果我們將其分配為“true”值,則物件將無法再在水平方向上移動。

線條物件在畫布中的預設行為

示例

讓我們看一個程式碼示例,以瞭解當未將lockMovementX 屬性分配為“true”值時,我們如何自由地在 X 軸或 Y 軸上移動線條物件。

<!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 behaviour of a Line object in the canvas</h2> <p> Drag the line object across the x-axis and y-axis to see that movement is allowed in both directions </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>

lockMovementX 作為鍵並傳遞“true”值

示例

在此示例中,我們將看到如何鎖定線條物件的水平移動。透過將lockMovementX 屬性分配為“true”值,我們實際上停止了水平方向上的移動。

<!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>Passing lockMovementX as key withtrue’ value</h2> <p> Drag the line object across the x-axis and y-axis to see that movement is no longer allowed in the horizontal direction </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, lockMovementX: "true", }); // Add it to the canvas canvas.add(line); </script> </body> </html>

更新於: 2022年10月25日

281 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.