如何使用 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