如何使用 FabricJS 在移动时设置文本框的边框不透明度?
fabricjshtml5 canvasjavascript
在本教程中,我们将使用 FabricJS 在移动时设置文本框的边框不透明度。我们可以自定义、拉伸或移动文本框中写入的文本。为了创建文本框,我们必须创建 fabric.Textbox 类的实例并将其添加到画布。我们可以使用 borderOpacityWhenMoving 属性在画布中移动文本框时更改其边框的不透明度。
语法
new fabric.Textbox(text: String, { borderOpacityWhenMoving: Number }: Object)
参数
text − 此参数接受 String,即我们想要在文本框内显示的文本字符串。
options(可选) − 此参数是一个对象,可为我们的文本框提供额外的自定义设置。使用此参数,可以更改与 borderOpacityWhenMoving 属性相关的对象的颜色、光标、笔触宽度等属性以及许多其他属性。
选项键
borderOpacityWhenMoving − 此属性接受一个数字,该数字指定我们希望在移动文本框时边框的不透明度。它允许我们在移动文本框对象时控制边框的不透明度。默认值为 0.4。
示例 1
显示 borderOpacityWhenMoving 属性的默认行为
让我们看一个代码示例,该示例显示了 boderOpacityWhenMoving 属性的默认行为。当我们选择文本框对象并将其在画布上移动时,选择边框的不透明度会从 1(完全不透明)更改为 0.4,这使其看起来有点半透明。
<!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>Displaying the default behaviour of borderOpacityWhenMoving property</h2> <p>You can select the textbox and drag it around to see that the border opacity changes from being fully opaque (1) to being translucent (0.4)</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("Small steps motivate. Big steps overwhelm.", { backgroundColor: "#ffe5b4", width: 400, top: 70, left: 110, borderColor: "red", }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>
示例 2
将 borderOpacityWhenMoving 作为键传递
让我们看一个代码示例,为 borderOpacityWhenMoving 属性分配一个值。在本例中,我们将值指定为 0。这告诉我们,当我们移动文本框时,边框不透明度将变为 0,并且不可见。
<!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 borderOpacityWhenMoving as key</h2> <p>You can select the textbox and drag it around to see that the borders are no longer visible when being moved</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("Small steps motivate. Big steps overwhelm.", { backgroundColor: "#ffe5b4", width: 400, top: 70, left: 110, borderColor: "red", borderOpacityWhenMoving: 0, }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>