javascript 如何在 Fabric.js 上获取鼠标坐标?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20463025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:32:56  来源:igfitidea点击:

How do I get mouse coordinates on Fabric.js?

javascriptjqueryhtml5-canvasfabricjs

提问by StAR_161

I'm trying to read the X coordinate of a mouse click on Fabric.js.

我正在尝试读取 Fabric.js 上鼠标单击的 X 坐标。

Here is my code. The console logs undefinedevery time.

这是我的代码。控制台undefined每次都记录。

var canvas = new fabric.Canvas('c1');
canvas.on('mouse:down', function(e){
  getMouse(e);
});

function getMouse(e) {
  console.log(e.clientX);
}

回答by StAR_161

The best fix is thismethod

最好的解决方法是这种方法

Implementation:

执行:

function getMouseCoords(event)
{
  var pointer = canvas.getPointer(event.e);
  var posX = pointer.x;
  var posY = pointer.y;
  console.log(posX+", "+posY);    // Log to console
}

回答by Skyvory

To get coordinates based on set width and height on the canvas itself, use layerX and layerY property.

要根据画布本身设置的宽度和高度获取坐标,请使用 layerX 和 layerY 属性。

canvas.on('mouse:move', function(options) {
    console.log(options.e.layerX, options.e.layerY);
});

回答by Rohan Kumar

Try this,

试试这个,

function getMouse(e) {
    console.log(e.e.clientX);
}

Demo

演示

Updated,as canvas eventstakes the optionsas an argumentnot an eventlike,

更新,canvas eventsoptionsargumentan event喜欢,

canvas.on('mouse:down', function(options){
   getMouse(options);// its not an event its options of your canvas object
});


function getMouse(options) {
    console.log(options);// you can check all options here
    console.log(options.e.clientX);
}

回答by Dudi

Maybe this will help:

也许这会有所帮助:

//Convert To Local Point
function toLocalPoint(event, canvas) {
var offset = fabric.util.getElementOffset(canvas.lowerCanvasEl), localX = event.e.clientX - offset.left, localY = event.e.clientY - offset.top;
return new fabric.Point(localX, localY);

}

}

回答by Bala Bhaskar

just use e.e.clientX

只需使用 eeclientX

or

或者

e.e.clientY

客户

for getting positions

获取职位