如何使用 FabricJS 创建一个在悬停于对象上时显示“禁止”光标的矩形?
在本教程中,我们将学习如何使用 FabricJS 创建一个在悬停于对象上时显示“禁止”光标的矩形。“禁止”是可用的原生光标样式之一,也可以在 FabricJS 画布中使用。FabricJS 提供了各种类型的鼠标光标,例如默认、全滚动、十字准星、列调整大小、行调整大小等,这些光标实际上是在后台重用了原生光标。`hoverCursor` 属性设置悬停在画布对象上时光标的样式。
语法
new fabric.Rect({ hoverCursor: String }: Object)参数
**选项(可选)** − 此参数是一个对象,它为我们的矩形提供了额外的自定义功能。使用此参数,可以更改与对象的许多属性,其中 `hoverCursor` 是一个属性,例如颜色、光标、描边宽度等。
选项键
**hoverCursor** − 此属性接受一个**字符串**,该字符串确定悬停在画布对象上时要使用的光标名称。使用此属性,我们可以设置悬停在此画布上的矩形对象上时的默认光标值。
示例 1
将hoverCursor 键传递给类
默认情况下,当我们将鼠标悬停在画布中的矩形对象上时,光标类型为“移动”。让我们看一个代码示例,该示例创建一个画布,在 FabricJS 中悬停在矩形对象上时显示**禁止**光标。
<!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 the hoverCursor Key to the class</h2>
<p>Hover over the rectangle to see the not-allowed cursor</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: 50,
top: 90,
width: 170,
height: 70,
strokeWidth: 3,
stroke: "#4169e1",
fill: "pink",
padding: 15,
hoverCursor: "not-allowed",
});
// Add it to the canvas
canvas.add(rect);
</script>
</body>
</html>示例 2
演示此效果仅影响实例
在此示例中,我们将 `hoverCursor` 键传递给矩形类,这意味着不会更改画布中每个对象的 `hoverCursor` 属性。更改仅会对该单个对象发生。这在下面的代码示例中进行了说明。
<!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>Demonstrating that it affects the instance only</h2>
<p>Hover over the rectangle objects to observe that the not-allowed cursor applies to the left object only. We have not used the <b>hoverCursor</b> property on the right object.</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 rect1 = new fabric.Rect({
left: 50,
top: 90,
width: 170,
height: 70,
strokeWidth: 3,
stroke: "#4169e1",
fill: "pink",
padding: 15,
hoverCursor: "not-allowed",
});
// Initiate another rectangle object
var rect2 = new fabric.Rect({
left: 325,
top: 90,
width: 170,
height: 70,
strokeWidth: 3,
stroke: "#ff69b4",
fill: "#fae7b5",
padding: 15,
});
// Add them to the canvas
canvas.add(rect1);
canvas.add(rect2);
</script>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP