简体   繁体   English

fabric.js抵消解决方案

[英]fabric.js Offset Solution

In dealing with offset with fabric.js - what is the best approach? 在处理与fabric.js的偏移时 - 最好的方法是什么?

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/ 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? 有一个更好的方法吗?

You have not factored in the positioning of the canvas element. 你没有考虑canvas元素的定位。 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 正如您在代码中看到的那样,canvas元素的坐标由: canvas._offset.leftcanvas._offset.top

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM