-->

How to freedraw Circle in fabricjs using mouse?

2020-08-01 04:55发布

问题:

I am using Fabricjs in my project and now working on drawing circle using Fabricjs library.

I am able to do it but it is not very proper on x-axis , as dragging on x-axis seems improper whereas dragging on y-axis works fine.

Can anybody fix it to work on any axis.

Also there are 2-3 questions on stackoverflow that are not properly answered regarding Circle out of which I asked 1 previously.

Here's the Fiddle of the work I have done so far: Draw Circle

Code : `

var canvas = new fabric.Canvas("canvas2");
var circle, isDown, origX, origY;

canvas.on('mouse:down', function(o){
isDown = true;
var pointer = canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
circle = new fabric.Circle({
    left: origX,
    top: origY,
    originX: 'left',
    originY: 'top',
    radius: pointer.x-origX,
    angle: 0,
    fill: '',
    stroke:'red',
    strokeWidth:3,
});
canvas.add(circle);
});

canvas.on('mouse:move', function(o){
if (!isDown) return;
var pointer = canvas.getPointer(o.e);
var radius = Math.abs(origY - pointer.y)/2;
if (radius > circle.strokeWidth) {
    radius -= circle.strokeWidth/2;
}
circle.set({ radius: radius});

if(origX>pointer.x){
    circle.set({originX: 'right' });
} else {
    circle.set({originX: 'left' });
}
if(origY>pointer.y){
    circle.set({originY: 'bottom'  });
} else {
    circle.set({originY: 'top'  });
}

canvas.renderAll();
});

canvas.on('mouse:up', function(o){
  isDown = false;
});

`

回答1:

See update fiddle. You have just to select the minimum or maximum from x and y when selecting the radius.

http://jsfiddle.net/8u1cqasa/17/

I modified (again) your mouse:move function to take in account both movements.

canvas.on('mouse:move', function(o){
    if (!isDown) return;
    var pointer = canvas.getPointer(o.e);
    var radius = Math.max(Math.abs(origY - pointer.y),Math.abs(origX - pointer.x))/2;
    if (radius > circle.strokeWidth) {
        radius -= circle.strokeWidth/2;
    }
    circle.set({ radius: radius});

    if(origX>pointer.x){
        circle.set({originX: 'right' });
    } else {
        circle.set({originX: 'left' });
    }
    if(origY>pointer.y){
        circle.set({originY: 'bottom'  });
    } else {
        circle.set({originY: 'top'  });
    }
    canvas.renderAll();
});