如何使用 FabricJS 创建一个在悬停于对象时显示“禁止”光标的画布?
在本文中,我们将使用 FabricJS 创建一个在悬停时显示“禁止”光标的画布。“禁止”是可用的原生光标样式之一,也可以在 FabricJS 画布中使用。FabricJS 提供各种类型的游标,例如默认、全滚动、十字准星、列调整大小、行调整大小等,这些游标在后台重用原生游标。`hoverCursor` 属性设置悬停在画布对象上时光标的样式。
语法
new fabric.Canvas(element: HTMLElement|String, { hoverCursor: String }: Object)参数
element − 此参数是<canvas> 元素本身,可以使用 `document.getElementById()` 或 <canvas> 元素的 ID 获取。FabricJS 画布将在此元素上初始化。
options (可选) − 此参数是一个对象,它为我们的画布提供额外的自定义功能。使用此参数,可以更改与画布相关的许多属性,例如颜色、光标、边框宽度等,其中 `hoverCursor` 是一个属性,我们可以用它来设置在悬停在画布对象上时的默认光标值。
示例 1
将 `hoverCursor` 键传递给类
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>Canvas with not-allowed cursor on hover over object using FabricJS</h2>
<p>Hover the mouse over the object to see how the cursor style changes.</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas", {
hoverCursor: "not-allowed",
});
// Creating an instance of the fabric.Circle class
var cir = new fabric.Circle({
radius: 40,
fill: "#008b8b",
left: 30,
top: 20,
});
// Adding it to the canvas
canvas.add(cir);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>示例 2
使用点表示法设置 `hoverCursor`
在这个示例中,我们有一个矩形对象和一个椭圆对象,通过将 `hoverCursor` 属性设置为“not-allowed”,当我们悬停在画布中的任何对象上时,我们的光标将变为“禁止”光标类型。
<!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>Canvas with not-allowed cursor on hover over objects using FabricJS</h2>
<p>There are two objects on this canvas. Hover the mouse over the objects to see how the cursor style changes.</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.hoverCursor = "not-allowed";
// Creating an instance of the fabric.Rect class
var rect = new fabric.Rect({
left: 180,
top: 80,
width: 90,
height: 150,
fill: "#4169e1",
angle: 82,
});
var ellipse = new fabric.Ellipse({
top: 76,
left: 210,
fill: "#cd5b45",
stroke: "#dcdcdc",
strokeWidth: 1,
rx: 30,
ry: 50,
});
// Adding it to the canvas
canvas.add(rect);
canvas.add(ellipse);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP