如何使用 FabricJS 禁用矩形的可选择性?


在这篇文章中,我们将学习如何使用 FabricJS 禁用矩形的可选择性。矩形是 FabricJS 提供的各种形状之一。为了创建矩形,我们必须创建一个 fabric.Rect 类的实例并将其添加到画布上。为了修改对象,我们必须在 FabricJS 中选择它。但是,我们可以使用 selectable 属性更改此行为。

语法

new fabric.Rect{ selectable: Boolean }: Object)

参数

  • 选项(可选) - 此参数是一个 对象,它为我们的矩形提供了额外的自定义功能。使用此参数,可以更改与对象的 selectable 属性相关的属性,例如颜色、光标、笔触宽度以及许多其他属性。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

选项键

  • selectable - 此属性接受一个 布尔值。当为其分配“false”值时,无法选择该对象进行修改。其默认值为 true。

示例 1

默认行为或当 selectable 属性设置为“True”时

让我们看一个代码示例,了解当默认情况下 selectable 属性设置为 True 时对象的行为。当 selectable 属性设置为 True 时,我们允许选择对象、在画布周围移动它并对其进行修改。

Open Compiler
<!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; selectable property is set to True</h2> <p>You can try moving the rectangle around the canvas or scaling it to prove that it's selectable.</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 rectangle object var rect = new fabric.Rect({ left: 105, top: 70, width: 170, height: 70, fill: "#dcdcdc", stroke: "#696969", strokeWidth: 5, }); // Add it to the canvas canvas.add(rect); </script> </body> </html>

示例 2

 将 selectable 属性作为键传递

在此示例中,我们将 False 值分配给 selectable 属性。这意味着我们不能再选择矩形对象进行修改。

Open Compiler
<!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 selectable property as key</h2> <p>You can try clicking on the rectangle to see that it is no longer selectable.</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 rectangle object var rect = new fabric.Rect({ left: 105, top: 70, width: 170, height: 70, fill: "#dcdcdc", stroke: "#696969", strokeWidth: 5, selectable: false, }); // Add it to the canvas canvas.add(rect); </script> </body> </html>

更新于: 2022-06-29

403 次查看

启动你的 职业生涯

通过完成课程获得认证

开始
广告