如何使用Fabricjs自由绘制椭圆?

时间:2015-12-05 03:18:08

标签: javascript jquery html5 html5-canvas fabricjs

以下是使用Fabricjs绘制圆圈的代码:Draw Circle using Mouse

我想为椭圆实现相同的效果。因为自由绘制圆将取决于半径,但我想绘制一个蛋形或椭圆形区域,半径对我没有帮助,因此我希望在这里使用椭圆。

免费绘图圈代码: `

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

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

`

任何人都可以吗?

1 个答案:

答案 0 :(得分:5)

你可以做其他形状的情况: How to freedraw Circle in fabricjs using mouse?



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

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

canvas.on('mouse:move', function(o){
    if (!isDown) return;
    var pointer = canvas.getPointer(o.e);
    var rx = Math.abs(origX - pointer.x)/2;
    var ry = Math.abs(origY - pointer.y)/2;
    if (rx > ellipse.strokeWidth) {
      rx -= ellipse.strokeWidth/2
    }
     if (ry > ellipse.strokeWidth) {
      ry -= ellipse.strokeWidth/2
    }
    ellipse.set({ rx: rx, ry: ry});
    
    if(origX>pointer.x){
        ellipse.set({originX: 'right' });
    } else {
        ellipse.set({originX: 'left' });
    }
    if(origY>pointer.y){
        ellipse.set({originY: 'bottom'  });
    } else {
        ellipse.set({originY: 'top'  });
    }
    canvas.renderAll();
});

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

<script type="text/javascript" src="http://www.deltalink.it/andreab/fabric/fabric.js" ></script>
<canvas id="canvas2" width=500 height=500 ></canvas>
&#13;
&#13;
&#13;