如何使用鼠标在fabricjs中自由圈? [英] How to freedraw Circle in fabricjs using mouse?

查看:391
本文介绍了如何使用鼠标在fabricjs中自由圈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用Fabricjs,现在正在使用Fabricjs库绘制圆形。

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

我能够做到但是它在x-上不是很合适轴,因为在x轴上拖动似乎不合适,而在y轴上拖动工作正常。

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.

另外有关于stackoverflow的2-3个问题没有得到正确回答,我之前曾问过1。

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

代码:
`

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

`

推荐答案

请参阅更新小提琴。
选择半径时,您只需从x和y中选择最小值或最大值。

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

这篇关于如何使用鼠标在fabricjs中自由圈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆