如何使用 FabricJS 在移動物件上建立帶文字游標的文字框?
在本教程中,我們將使用 FabricJS 建立一個文字框,當滑鼠懸停在物件上時,文字框會顯示文字游標。text 是可用的原生 游標 樣式之一,它也可以在 FabricJS 畫布中使用。FabricJS 提供了各種型別的遊標,例如預設、全部滾動、十字線、列調整大小、行調整大小等,它們在後臺重用了原生遊標。moveCursor 屬性在畫布中移動物件時設定游標的樣式。
語法
new fabric.Textbox(text: String, { moveCursor: String }: Object)
引數
text − 此引數接受一個字串,它是我們想要在文字框內顯示的文字字串。
options(可選)− 此引數是一個物件,它為我們的文字框提供了額外的自定義選項。使用此引數可以更改顏色、游標、描邊寬度以及與 moveCursor 屬性相關的許多其他與物件相關的屬性。
選項鍵
moveCursor − 此屬性接受一個字串,允許我們在畫布上移動此文字框物件時設定預設游標值。該值確定在移動畫布物件時要使用的游標型別。
示例 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>Default cursor value when object is moved around the canvas</h2> <p>Move the textbox to see the default style of cursor</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("Whatever you are, be a good one.", { backgroundColor: "#fffff0", width: 400, left: 110, top: 70, fill: "#e1a95f", strokeWidth: 2, stroke: "#a40000", textAlign: "center", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>
示例 2
將 moveCursor 屬性作為鍵傳遞並附帶值
在此示例中,我們將moveCursor 鍵作為值“text”傳遞給文字框類。這將確保當我們在畫布中移動物件時,游標值為 text。這在下面的程式碼示例中進行了說明:
<!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 the moveCursor property as key with a value</h2> <p>Move the cursor around the textbox and observe that the cursor style has now changed to "text".</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("Whatever you are, be a good one.", { backgroundColor: "#fffff0", width: 400, left: 110, top: 70, fill: "#e1a95f", strokeWidth: 2, stroke: "#a40000", moveCursor: "text", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>
廣告