How to freedraw Circle in fabricjs using mouse?

孤人 提交于 2019-12-06 13:52:03

问题


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();
});


来源:https://stackoverflow.com/questions/33958845/how-to-freedraw-circle-in-fabricjs-using-mouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!