Wai Yan Hein
Wai Yan Hein

Reputation: 14791

Getting current cursor position on the clicked object in Fabric.js

I am developing a Web application that involves HTML canvas feature. I am using Fabric.JS - http://fabricjs.com/ to render objects on it. In Fabric.Js, I can implement event listeners to the object as in this link- http://fabricjs.com/.

I am now adding an image object to the canvas and implement the mouse event listener to that image object. When the image object on the canvas is clicked, I would like to retrieve the position (x, y) of the image clicked. But it is always returning zero.

I am adding image object to the canvas like this:

var imgInstance = new fabric.Image(js_left_temp_img, {
                        left: 0,
                        top: 0
                    });

                    imgInstance.scale(0.1)
                    imgInstance.selectable = false;
                    imgInstance.set('selectable', false)
                    $canvas.add(imgInstance);

Then I set up the event listener to the image object like this and try to retrieve the clicked position of image object like this.

imgInstance.on('mousedown', function(e){
                        //alert('Image clicked')
                        console.log(e.target.left + " - " + e.target.top)

                    });

When I click on the image, it fires the event, but the left and top values are always returning zero. How can I retrieve the current clicked left and top or x and y position of the image in the event listener?

Upvotes: 1

Views: 2865

Answers (1)

Durga
Durga

Reputation: 15604

Use object.getLocalPointer()

DEMO

var canvas = new fabric.Canvas('canvas'),imgInstance;
canvas.on('object:selected', function(e) {
});

fabric.Image.fromURL('http://fabricjs.com/assets/pug.jpg', function(img) {
  img.set({
    left: 0,
    top: 0,
    scaleX: 0.3,
    scaleY: 0.3
  });
  canvas.add(img);
  img.on('mousedown',function(options){
   var pointer = this.getLocalPointer(options.e);
   console.log(pointer);
  })
});
canvas{
 border:2px solid #000;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id='canvas' width=500 height=400>

Upvotes: 1

Related Questions