在本教程中,我们将学习如何使用 fabricjs 禁用 itext 的选择性。 itext 类是在 fabricjs 版本 1.4 中引入的,它扩展了 fabric.text 并用于创建 itext 实例。 itext 实例使我们可以自由选择、剪切、粘贴或添加新文本,而无需额外配置。还有各种支持的按键组合和鼠标/触摸组合使文本具有交互性,而 text 中未提供这些组合。
然而,基于 itext 的 textbox 允许我们调整文本矩形的大小并自动换行。对于 itext 来说情况并非如此,因为高度不会根据换行进行调整。我们可以通过使用各种属性来操作 itext 对象。为了修改一个对象,我们必须在 fabricjs 中选择它。但是,我们可以通过使用 selectable 属性来更改此行为。
语法new fabric.itext(text: string, { selectable: boolean }: object)
参数text - 此参数接受 string,它是我们要在 itext 对象中显示的文本字符串。
选项(可选) - 此参数是一个对象,它为我们的对象提供额外的自定义。使用此参数,可以更改与可选择属性的对象相关的颜色、光标、描边宽度和许多其他属性。
选项键selectable - 此属性接受布尔值。当为其分配“假”值时,无法选择该对象进行修改。它的默认值为 true。
示例 1默认行为或可选属性设置为“true”时
让我们看一个代码示例,以了解默认情况下 selectable 属性设置为 true 时对象的行为。当 selectable 属性设置为 true 时,我们可以选择一个对象,在画布上移动它并对其进行修改。
<!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 or when selectable property is set to ‘true’</h2> <p>you can try moving the itext object 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 an itext object var itext = new fabric.itext( add sample text here.lorem ipsum dolor sit amet,{ width: 300, left: 50, top: 70, fill: #6ae18b, } ); // add it to the canvas canvas.add(itext); </script></body></html>
示例 2将可选属性作为具有“false”值的键传递
在此示例中,我们为可选属性分配了一个假值。这意味着我们无法再选择 itext 对象进行修改。
<!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 with “false” value</h2> <p>you can see that the itext object 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 an itext object var itext = new fabric.itext( add sample text here.lorem ipsum dolor sit amet,{ width: 300, left: 50, top: 70, fill: #6ae18b, selectable: false, } ); // add it to the canvas canvas.add(itext); </script></body></html>
以上就是如何使用 fabricjs 禁用 itext 的选择性?的详细内容。