如何使用 FabricJS 在移动对象上创建带有十字准星光标的文本框?
在本教程中,我们将使用 FabricJS 创建一个在移动对象上带有十字准星光标的文本框。十字准星是可用的原生光标样式之一,也可以在 FabricJS 画布中使用。FabricJS 提供各种类型的游标,例如默认、全滚动、十字准星、列调整大小、行调整大小等,这些游标在底层重用了原生游标。`moveCursor` 属性设置移动画布中对象时光标的样式。
语法
new fabric.Textbox(text: String, { moveCursor: String }: Object)参数
text − 此参数接受一个字符串,即我们想要在文本框内显示的文本字符串。
options (可选) − 此参数是一个对象,它为我们的文本框提供额外的自定义选项。使用此参数可以更改与对象相关的颜色、光标、笔划宽度以及许多其他属性,其中`moveCursor` 是一个属性。
选项键
moveCursor − 此属性接受一个字符串,允许我们在画布上移动此文本框对象时设置默认光标值。该值决定了移动画布对象时要使用的光标类型。
示例 1
移动对象时默认光标值
默认情况下,当我们在画布中移动文本框对象时,光标类型为`move`。让我们来看一个代码示例来理解这一点。
<!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 cursor value when object is moved around the canvas</h2>
<p>Move the cursor around the textbox object and observe that the defaultcursor style is "move"</p>
<canvas id="canvas"gt;</canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a textbox object
var textbox = new fabric.Textbox("Stay hungry. Stay foolish.", {
backgroundColor: "#fffff0",
width: 400,
left: 110,
top: 70,
fill: "#e1a95f",
strokeWidth: 2,
stroke: "#a40000",
textAlign: "center",
});
// Add it to the canvas
canvas.add(textbox);
</script>
</body>
</html>示例 2
将 moveCursor 属性作为键值对传递
在这个例子中,我们将`moveCursor` 键作为值为“crosshair”传递给文本框类。这将确保当我们在画布中移动我们的对象时,光标值为十字准星。这在下面的代码示例中进行了说明:
<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 the moveCursor property as key with a value</h2>
<p>Move the cursor around the textbox object and observe that now the cursor style has changed to "crosshair"</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 textbox object
var textbox = new fabric.Textbox("Stay hungry. Stay foolish.", {
backgroundColor: "#fffff0",
width: 300,
left: 110,
top: 70,
fill: "#e1a95f",
strokeWidth: 2,
stroke: "#a40000",
textAlign: "center",
moveCursor: "crosshair",
});
// Add it to the canvas
canvas.add(textbox);
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP