StAR_161
StAR_161

Reputation: 658

How do I get mouse coordinates on Fabric.js?

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

Here is my code. The console logs undefined every time.

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

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

Upvotes: 12

Views: 21923

Answers (5)

Dudi
Dudi

Reputation: 3079

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);

}

Upvotes: -1

Skyvory
Skyvory

Reputation: 373

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

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

Upvotes: 8

StAR_161
StAR_161

Reputation: 658

The best fix is this method

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
}

Upvotes: 36

Bala Bhaskar
Bala Bhaskar

Reputation: 11

just use e.e.clientX

or

e.e.clientY

for getting positions

Upvotes: -1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

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

Demo

Updated, as canvas events takes the options as an argument not an event like,

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);
}

Upvotes: 4

Related Questions