如何使用 FabricJS 查找点击的多段线对象上的当前光标位置?
我们可以通过创建fabric.Polyline的实例来创建一个多段线对象。多段线对象可以由一组连接的直线段来表征。因为它属于 FabricJS 的基本元素之一,我们也可以通过应用角度、不透明度等属性轻松地对其进行自定义。
为了找到点击的多段线对象上的当前光标位置,我们使用getLocalPointer方法。
语法
getLocalPointer( e, pointer ): Object
参数
e − 此参数接受一个事件,表示要操作的事件。
pointer (可选) − 此参数是一个对象,表示要操作的指针。此参数是可选的。
示例 1:使用 getLocalPointer 方法
让我们来看一个代码示例,说明如何使用getLocalPointer方法找到相对于多段线对象的指针坐标。当我们点击多段线时,会触发一个 mousedown 事件,这使我们能够检索多段线实例当前点击的左和上位置。
<!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>Using the getLocalPointer method</h2>
<p>You can click on the polyline object while the console from dev tools is opened to see that the logged output contains the x and y coordinates </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 polyline instance
var polyline = new fabric.Polyline(
[
{ x: 500, y: 20 },
{ x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 200 },
{ x: 350, y: 60 },
],
{
fill: "green",
stroke: "blue",
strokeWidth: 20,
}
);
// Add it to the canvas
canvas.add(polyline);
// Using getLocalPointer method
polyline.on("mousedown", function (options) {
var pointer = this.getLocalPointer(options.e);
console.log("Coordinates of the pointer relative to the object are: ", pointer);
});
</script>
</body>
</html>
示例 2:使用 getLocalPointer 方法和不同的事件监听器
让我们来看一个代码示例,了解如何使用不同的事件监听器来检索当前光标位置的“x”和“y”坐标。在这里,我们将值设置为“skewing”,这确保在水平或垂直方向倾斜对象时触发事件。
通过按住Shift 键然后沿水平或垂直方向拖动可以实现倾斜。您可以打开控制台,查看在对象从控件进行倾斜时是否触发了事件。
<!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>Using the getLocalPointer method and using a different event listener </h2>
<p>You can press the shift-key and drag the middle edge along the x or yaxis to skew the object while the console from dev tools is opened to see that the logged output contains the x and y coordinates </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 polyline instance
var polyline = new fabric.Polyline(
[
{ x: 500, y: 20 },
{x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 200 },
{ x: 350, y: 60 },
],
{
fill: "green",
stroke: "blue",
strokeWidth: 20,
lockMovementX: true,
lockMovementY: true,
}
);
// Add it to the canvas
canvas.add(polyline);
// Using getLocalPointer method
polyline.on("skewing", function (options) {
var pointer = this.getLocalPointer(options.e);
console.log(
"Coordinates of the pointer relative to the object are: ", pointer
);
});
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP