fabricjs editing textbox inside fabric Group

by rahulr

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.4.0/fabric.min.js"></script>
<h4>fabricjs editing textbox inside fabric Group</h4>
<canvas id="canvas"></canvas>

CSS

#canvas {
  width:300px;
  height:300px;
  border: 1px solid #333;
}

TypeScript

var canvas = new fabric.Canvas('canvas');
canvas.setWidth(300);
canvas.setHeight(300);

function createGroup() {
	let circle = new fabric.Circle({
  	radius:40,
    fill: 'rgba(200, 0, 0, 0.3)',
    originX: 'center',
    originY: 'center',
  });
  
  let text = new fabric.Textbox("AJLoveChina", {
  	originX: 'center',
    originY: 'center',
    textAlign: 'center',
    fontSize: 12,
  })
  
  let group = new fabric.Group([circle, text], {
   	left: 100,
    top: 100,
    originX: 'center',
    originY: 'center',
  });
  
  group.on('mousedblclick', () => {
    // textForEditing is temporary obj, 
    // and will be removed after editing
  	let textForEditing = new fabric.Textbox(text.text, {
      originX: 'center',
      originY: 'center',
      textAlign: text.textAlign,
      fontSize: text.fontSize,
      
      left: group.left,
      top: group.top,
    })
    
    // hide group inside text
    text.visible = false;
    // note important, text cannot be hidden without this
    group.addWithUpdate();
    
    textForEditing.visible = true;
    // do not give controls, do not allow move/resize/rotation on this 
    textForEditing.hasConstrols = false;

    
    // now add this temporary obj to canvas
    canvas.add(textForEditing);
    canvas.setActiveObject(textForEditing);
    // make the cursor showing
    textForEditing.enterEditing();
    textForEditing.selectAll();
    
    
    // editing:exited means you click outside of the textForEditing
    textForEditing.on('editing:exited', () =>{
    	let newVal = textForEditing.text;
      let oldVal = text.text;
      
      // then we check if text is changed
      if (newVal !== oldVal) {
      	text.set({
        	text: newVal,
          visible: true,
        })
        
        // comment before, you must call this
        group.addWithUpdate();
        
        // we do not need textForEditing anymore
        textForEditing.visible = false;
        canvas.remove(textForEditing);
        
        //...