1

I am using fabricJs library to create rectangles and want to get mouse position after zooming

I use this code to start drawing the rectangle, in scale = 1, it works right but after i get zoom in for example and click i get the rectangle start point in the point not i click on, what cause this ?

// Create new rectangle
canvas.on('mouse:down', function (options) {
    if (canvas.getActiveObject()) {
        return false;
    }

    started = true;

    ex = (posx);
    ey = (posy);

    var colors = ['#FF8080', '#D5D5E6', '#C0F2C0', '#8080E4', '#CCCCAA'];
    var rectangle_color = colors[Math.floor(Math.random() * colors.length)];

    var square = new fabric.Rect({
        width: 0,
        height: 0,
        left: ex,
        top: ey,
        fill: rectangle_color
    });
    var square = new fabric.Rect({ width: 0, height: 0, left: ex, top: ey, fill: rectangle_color });

    canvas.add(square);
    canvas.setActiveObject(square);
});
ahmad soliman
  • 141
  • 1
  • 2
  • 14
  • Maybe this helps, basically the zoom proportion needs to be added to the calculation of the position you clicked on. http://stackoverflow.com/questions/30002361/image-zoom-centered-on-mouse-position – Lau Jun 16 '15 at 11:30
  • Thanks it's very userful for me – ahmad soliman Jun 16 '15 at 13:33

1 Answers1

3

You need your real coordinates of your mouse not some scope declared posx and posy:

canvas.on('mouse:down', function (event) {
    if (canvas.getActiveObject()) {
        return false;
    }
    var pointer = canvas.getPointer(event.e);
    var posx = pointer.x;
    var posy = pointer.y;
    //... 
    //your code
    //...
}
SilentTremor
  • 4,747
  • 2
  • 21
  • 34
  • Or you can look here: http://stackoverflow.com/questions/20463025/how-do-i-get-mouse-coordinates-on-fabric-js/34518837#34518837 – Dudi Dec 29 '15 at 21:15