如何使用 Fabric.js 自由绘制圆圈?

我正在使用 FabricJS 在画布上画圆:

I am using FabricJS to draw circle in canvas:

var circle = new fabric.Circle({radius: 100,
                 fill: '',
                 stroke: 'red',
                 strokeWidth: 3,
                 originX: 'center', 
                 originY: 'center' 
               });
            var text = new fabric.Text('HELLO WORLD.',
                        {  fontSize: 30, 
                            originX: 'center', 
                            originY: 'center',
                            fill : 'red' 
                          });
            var group = new fabric.Group([ circle, text ], { 
                                           left: 150, top: 100
                                         });
            canvas.add(group);

这段代码画了一个普通的圆圈,但我需要用鼠标自由地画圆圈.任何代码帮助将不胜感激.

This code draws a normal circle but I need to freely draw circle with mouse. Any code help will be appreciated.

推荐答案

根据你之前绘制矩形的代码 http://jsfiddle.net/Subhasish2015/8u1cqasa/2/ 这里是画圆的代码:

According to your previous code for drawing rectangle http://jsfiddle.net/Subhasish2015/8u1cqasa/2/ Here is the code for drawing circle:

$(document).ready(function(){
//Getting the canvas
var canvas1 = new fabric.Canvas("canvas2");
var freeDrawing = true;
var divPos = {};
var offset = $("#canvas2").offset();
$(document).mousemove(function(e){
    divPos = {
        left: e.pageX - offset.left,
        top: e.pageY - offset.top
    };
});
$('#2').click(function(){       

    //Declaring the variables
    var isMouseDown=false;
    var refCircle;

    //Setting the mouse events
    canvas1.on('mouse:down',function(event){           
        isMouseDown=true;            
        if(freeDrawing) {
        var circle=new fabric.Circle({
            left:divPos.left,
            top:divPos.top,                
            radius:0,
            stroke:'red',
            strokeWidth:3,
            fill:''
        });
        canvas1.add(circle);
        refCircle=circle;  //**Reference of rectangle object
       }

    });

    canvas1.on('mouse:move', function(event){
        if(!isMouseDown)
        {
            return;
        }
        //Getting yhe mouse Co-ordinates
        if(freeDrawing) {
            var posX=divPos.left;
            var posY=divPos.top;    
            refCircle.set('radius',Math.abs((posX-refCircle.get('left'))));            
            canvas1.renderAll(); 
        }
    });

    canvas1.on('mouse:up',function(){
        canvas1.add(refCircle);
        //alert("mouse up!");
        isMouseDown=false;
        //freeDrawing=false;  // **Disables line drawing
    });
 });
 });

相关文章