如何使用 FabricJS 鎖定文字框的旋轉?


在本教程中,我們將學習如何使用 FabricJS 鎖定文字框的旋轉。就像我們可以在畫布中指定文字框物件的 位置、顏色、不透明度和尺寸一樣,我們還可以指定是否允許旋轉。這可以透過使用 lockRotation 屬性來實現。

語法

new fabric.Textbox(text: String, { lockRotation : Boolean }: Object)

引數

  • text − 此引數接受一個字串,它是我們想要在文字框內顯示的文字字串。

  • options(可選) − 此引數是一個物件,它為我們的文字框提供了額外的自定義功能。使用此引數,可以更改與物件的許多屬性相關的屬性,例如顏色、游標、筆劃寬度等等,其中lockRotation 就是一個屬性。

選項鍵

  • lockRotation − 此屬性接受一個布林值。如果我們將其賦值為“true”,則物件的旋轉將被鎖定。

示例 1

畫布中文字框物件的預設行為

讓我們來看一個程式碼示例,以瞭解當不使用lockRotation 屬性時文字框物件的預設行為。預設情況下,我們可以逆時針或順時針旋轉文字框物件。

<!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 Textbox object in the canvas</h2> <p>You can try rotating the Textbox using rotation handle to see the default behaviour</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 textbox object var textbox = new fabric.Textbox("Don’t let yesterday take up too much of today.", { width: 400, left: 110, top: 70, fill: "orange", strokeWidth: 2, stroke: "green", textAlign: "center", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>

示例 2

lockRotation 作為鍵傳遞,值為‘true’

在此示例中,我們將看到如何透過使用lockRotation 屬性來停止文字框物件旋轉的能力。正如我們所看到的,一旦我們嘗試旋轉文字框物件,就會顯示一個不允許的游標。這意味著旋轉操作不再允許。

<!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 lockRotation as key withtrue’ value</h2> <p>Now we see a not-allowed cursor when we try to rotate the textbox</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 textbox object var textbox = new fabric.Textbox("Don’t let yesterday take up too much of today.", { width: 400, left: 110, top: 70, fill: "orange", strokeWidth: 2, stroke: "green", textAlign: "center", lockRotation: true, }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>

更新於: 2022年8月2日

179 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.