如何使用 FabricJS 设置文本框的编辑模式?
fabricjshtml5 canvasjavascript
在本教程中,我们将学习如何使用 FabricJS 启用文本框的编辑模式。就像我们可以在画布中指定文本框对象的位置、颜色、不透明度和尺寸一样,我们也可以在文本框中编辑文本。可以使用 editable 属性启用或禁用此功能。
语法
new fabric.Textbox(text: String, { editable : Boolean }: Object)
参数
text − 此参数接受 String,这是我们想要在文本框内显示的文本字符串。
options (可选) − 此参数是一个对象,它为我们的文本框提供额外的自定义。使用此参数,可以更改与具有 editable 属性的对象相关的属性(例如颜色、光标、笔触宽度和许多其他属性)。
选项键
editable:此属性接受 布尔 值。如果我们为其分配"true"值,则允许编辑文本框内的文本。其默认值为 true。
示例 1
画布中文本框对象的默认行为
让我们看一个代码示例,以了解未使用 editable 属性时文本框对象的默认行为。默认情况下,我们可以编辑文本框对象内的文本。
<!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 double click on the Textbox and edit the text</p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // 初始化一个 textbox 文本框对象 var textbox = new fabric.Textbox("It doesn't matter how slow you go, as long as you don't stop.", { width: 400, left: 110, top: 70, fill: "orange", stroke: "green", textAlign: "center", }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>
示例 2
将 editable 作为键传递,并将值设置为"false"
在此示例中,我们将了解如何使用 editable 属性使文本框对象内的文本不可编辑。如我们所见,虽然我们可以选择文本框对象,但无法再编辑其中的文本。
<!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 editable as key with "false" value</h2> <p>You can double-click on the textbox to see that the text is not editable</p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // 初始化一个 textbox 文本框对象 var textbox = new fabric.Textbox("It doesn't matter how slow you go, as long as you don't stop.", { width: 400, left: 110, top: 70, fill: "orange", stroke: "green", textAlign: "center", editable: false, }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>