Search code examples
javascriptfabricjsfabricjs2

How to disable rotating point on a group?


I have some elements in my canvas and they don't have a rotating point

hasRotatingPoint: false

I actually want to apply it for the entire canvas, so if I click & drag to select multiple elements and create a group I want hasRotatingPoint: false to be applied there as well.

In the example bellow it works when I select a single element, but it doesn't disable the point when I create a group.

How can I disable hasRotatingPoint for groups? (Or the entire canvas)

var fabric = window.fabric
var canvas = new fabric.Canvas('canvas', {})

var opts = {
  hasRotatingPoint: false,
  left: 10,
}
canvas.add(new fabric.Textbox('blahblah', { ...opts, top: 60 }))
canvas.add(new fabric.Textbox('blahblah', { ...opts, top: 100 }))

canvas.setWidth(300)
canvas.setHeight(200)
canvas {
  border: 1px dashed red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.4/fabric.min.js"></script>

<canvas id="canvas" width="300" height="200"></canvas>


Solution

  • Whenever a new ActiveSelection is created, fabric.Canvas fires a selection:created event with the instance of fabric.ActiveSelection attached to it as target. So you can listen to this event and change the selection's hasRotatingPoint accordingly.

    To cover the case when a user selects one object then adds another one to the selection via Shift+click, you should also listen to selection:updated event, as this will reset hasRotatingPoint to default.

    var fabric = window.fabric
    var canvas = new fabric.Canvas('canvas', {})
    
    var opts = {
      hasRotatingPoint: false,
      left: 10,
    }
    canvas.add(new fabric.Textbox('blahblah', { ...opts, top: 60 }))
    canvas.add(new fabric.Textbox('blahblah', { ...opts, top: 100 }))
    
    canvas.setWidth(300)
    canvas.setHeight(200)
    
    canvas.on('selection:created', function (e) {
      const activeSelection = e.target
      activeSelection.set({hasRotatingPoint: false})
    })
    
    // fired e.g. when you select one object first,
    // then add another via shift+click
    canvas.on('selection:updated', function (e) {
      const activeSelection = e.target
      if (activeSelection.hasRotatingPoint) {
        activeSelection.set({hasRotatingPoint: false})
      }
    })
    canvas {
      border: 1px dashed red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.4/fabric.min.js"></script>
    
    <canvas id="canvas" width="300" height="200"></canvas>

    If you want to make it a default behavior for all objects, you can patch fabric.Object prototype, since all objects (ActiveSelection not being an exception) are extended from it.

    fabric.Object.prototype.hasRotatingPoint = false
    canvas.add(new fabric.Textbox('blahblah')
    //...