Search code examples
javascriptfabricjs

Fabric.js - Attach object creation to mouse click


When you create a new fabric object, you can specify the location for it to appear on the canvas. Is there a way to attach the generated object to the mouse and then place the object on click (or touch)?

E.g. way to generate a circle which appears on the canvas.

var circle = new fabric.Circle({
  radius: 20, fill: 'green', left: 100, top: 100
});

Solution

  • It's fairly easy to update the position of an object to match that of the mouse's position and on mouse:up clone that object and place it on the canvas.

    var canvas = new fabric.Canvas('c');
    
    var mousecursor = new fabric.Circle({ 
      left: 0, 
      top: 0, 
      radius: 5, 
      fill: '#9f9', 
      originX: 'right', 
      originY: 'bottom',
    })
    
    canvas.add(mousecursor);
    
    canvas.on('mouse:move', function(obj) {
      mousecursor.top = obj.e.y - mousecursor.radius;
      mousecursor.left = obj.e.x - mousecursor.radius;
      canvas.renderAll()
    })
    
    canvas.on('mouse:out', function(obj) {
      // put circle off screen
      mousecursor.top = -100;
      mousecursor.left = -100;
      canvas.renderAll()
    })
    
    canvas.on('mouse:up', function(obj) {
      canvas.add(mousecursor.clone())
      canvas.renderAll()
    })
    canvas {
        border: 1px solid #ccc;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.js"></script>
    
    <canvas id="c" width="600" height="600"></canvas>