最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to free draw circle using Fabric.js? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Oct 13, 2015 at 19:31 maxshuty 10.7k13 gold badges69 silver badges86 bronze badges asked Oct 13, 2015 at 19:29 graphics123graphics123 1,2914 gold badges22 silver badges63 bronze badges 3
  • Certainly, there is a jump from drawing a static shape to drawing something based on user input. This question es off as, "I don't know what to do next, so will someone do this next [big] step for me." Instead, I suggest hitting up Google, and doing some more research or tutorials before hitting up StackOverflow for answers like this, as-is, you probably won't get answers from this question. – rodamn Commented Oct 13, 2015 at 20:35
  • To help you get on your way, I suggest that you begin to consider the user-interaction for drawing your shape. The two most mon ways to draw circles are: first-click indicates the center, and the second click indicates the radius from the first-click. Alternatively, two clicks can indicate the top-left-bottom-right bounding box for the circle. – rodamn Commented Oct 13, 2015 at 20:40
  • Okay I have done something for rectangle here : jsfiddle/Subhasish2015/8u1cqasa/2 can we do something for Circle in a similar way? – graphics123 Commented Oct 14, 2015 at 5:56
Add a ment  | 

4 Answers 4

Reset to default 7

According to your previous code for drawing rectangle http://jsfiddle/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
    });
 });
 });

var Circle = (function() {
  function Circle(canvas) {
    this.canvas = canvas;
    this.className = 'Circle';
    this.isDrawing = false;
    this.bindEvents();
  }

  Circle.prototype.bindEvents = function() {
    var inst = this;
    inst.canvas.on('mouse:down', function(o) {
      inst.onMouseDown(o);
    });
    inst.canvas.on('mouse:move', function(o) {
      inst.onMouseMove(o);
    });
    inst.canvas.on('mouse:up', function(o) {
      inst.onMouseUp(o);
    });
    inst.canvas.on('object:moving', function(o) {
      inst.disable();
    })
  }

  Circle.prototype.onMouseUp = function(o) {
    var inst = this;
    inst.disable();
  };

  Circle.prototype.onMouseMove = function(o) {
    var inst = this;
    if (!inst.isEnable()) {
      return;
    }

    var pointer = inst.canvas.getPointer(o.e);
    var activeObj = inst.canvas.getActiveObject();

    activeObj.stroke = 'red',
      activeObj.strokeWidth = 5;
    activeObj.fill = 'red';

    if (origX > pointer.x) {
      activeObj.set({
        left: Math.abs(pointer.x)
      });
    }

    if (origY > pointer.y) {
      activeObj.set({
        top: Math.abs(pointer.y)
      });
    }

    activeObj.set({
      rx: Math.abs(origX - pointer.x) / 2
    });
    activeObj.set({
      ry: Math.abs(origY - pointer.y) / 2
    });
    activeObj.setCoords();
    inst.canvas.renderAll();
  };

  Circle.prototype.onMouseDown = function(o) {
    var inst = this;
    inst.enable();

    var pointer = inst.canvas.getPointer(o.e);
    origX = pointer.x;
    origY = pointer.y;

    var ellipse = new fabric.Ellipse({
      top: origY,
      left: origX,
      rx: 0,
      ry: 0,
      transparentCorners: false,
      hasBorders: false,
      hasControls: false
    });

    inst.canvas.add(ellipse).setActiveObject(ellipse);
  };

  Circle.prototype.isEnable = function() {
    return this.isDrawing;
  }

  Circle.prototype.enable = function() {
    this.isDrawing = true;
  }

  Circle.prototype.disable = function() {
    this.isDrawing = false;
  }

  return Circle;
}());




var canvas = new fabric.Canvas('canvas');
var circle = new Circle(canvas);
<script src="https://cdnjs.cloudflare./ajax/libs/fabric.js/1.7.17/fabric.min.js"></script>
 Please draw circle here

<div id="canvasContainer">
  <canvas id="canvas" width="400" height="400" style="border: solid 1px"></canvas>
</div>

Here is the detail blog with jsfiddle - https://blog.thirdrocktechkno./sketching-circle-of-a-html5-canvas-using-the-fabricjs-f7dbfa20cf2d

Here is an example of drawing a rectangle which I carefully made and works for latest versions. Krunan example seems to work OK- just in case this is a rectangle free drawing implementation that doesn't use DOM apis like e.clientX, offsetLeft, etc to track the coords, but fabric.js APIs only which I think is safer. Also unregister event listeners - I'm still trying to refine it since I need free drawing support for my project - Since there is no official support for this I wanted to reference the example here for others.

https://cancerberosgx.github.io/demos/misc/fabricRectangleFreeDrawing.html

An easy way to add a Circle to a canvas:

canvas.add(new fabric.Circle({ radius: 30, fill: "green", top: 100, left: 100 }));
发布评论

评论列表(0)

  1. 暂无评论