fabric.js Offset Solution

2019-06-11 13:44发布

问题:

In dealing with offset with fabric.js - what is the best approach?

I'm basically allowing a user to draw a box, and I want to make sure I have the box drawn at the exact start and ending coordinates of the dragging action.

http://jsfiddle.net/mojo5000/P7gAC/4/

...
    left: x + width/2 - 8, 
    top: y + height/2 - 8, 
...

I basically had to a little rigging with the left and top values. It seems to work. Is there a better way to do this?

回答1:

You have not factored in the positioning of the canvas element. Use the following:

var canvas = new fabric.Canvas('c');

canvas.on("after:render", function(){canvas.calcOffset();});

var started = false;
var x = 0;
var y = 0;
var width = 0;
var height = 0;

canvas.on('mouse:down', function(options) {
  //console.log(options.e.clientX, options.e.clientY);

  x = options.e.clientX;
  y = options.e.clientY;

  canvas.on('mouse:up', function(options) {

    width = options.e.clientX - x;
    height = options.e.clientY - y;   

    var square = new fabric.Rect({

        width: width, 
        height: height, 
        left: x + width/2 - canvas._offset.left, 
        top: y + height/2 - canvas._offset.top, 
        fill: 'red',
        opacity: .2
    });
    canvas.add(square);
    canvas.off('mouse:up');
    $('#list').append('<p>Test</p>');

  });

});

As you can see in the code, the coordinates of the canvas element are given by: canvas._offset.left and canvas._offset.top