如何使用 FabricJS 设置文本框选择的背景颜色?

fabricjshtml5 canvasjavascript

在本教程中,我们将学习如何使用 FabricJS 设置文本框选择的背景颜色。我们可以自定义、拉伸或移动文本框中写入的文本。为了创建文本框,我们必须创建 fabric.Textbox 类的实例并将其添加到画布。我们可以在主动选择对象时更改其尺寸、旋转或操作它。我们可以使用 selectionBackgroundColor 属性更改文本框选择的背景颜色。

语法

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

参数

  • text − 此参数接受 String,这是我们想要在文本框内显示的文本字符串。

  • options(可选) − 此参数是一个对象,它为我们的文本框提供额外的自定义。使用此参数,可以更改与 selectionBackgroundColor 属性相关的对象的颜色、光标、笔触宽度等属性以及许多其他属性。

选项键

  • selectionBackgroundColor  此属性接受 String 值。分配的值将决定所选内容的背景颜色。

示例 1

未使用 selectionBackgroundColor 属性时的默认颜色

让我们看一个代码示例,以了解未使用 selectionBackgroundColor 属性时所选内容的显示方式。从这个示例中我们可以看出,所选内容区域或对象后面的区域没有颜色。

<!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 colour when selectionBackgroundColor property is not used</h2> <p>You can select the textbox to see that the selection area has no colour</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("Everyone smiles in the same language.", { width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "blue", textAlign: "center", }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>

示例 2

selectionBackgroundColor 属性作为键传递

在此示例中,我们为 selectionBackgroundColor 属性分配一个值。在本例中,我们向其传递了十六进制值"#e0ffff",这是一种浅青色,因此选择区域看起来就是这种颜色。

<!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 selectionBackgroundColor property as key</h2> <p>You can select the textbox to see that the selection area now has a light cyan colour</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("Everyone smiles in the same language.", { width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "blue", textAlign: "center", selectionBackgroundColor: "#e0ffff", }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>

相关文章