Insert Chars Bug

FabricJS

by Eugene Vilder

HTML

<script src="http://fabricjs.com/lib/fabric.js"></script>
<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>

JavaScript

const canvas = new fabric.Canvas('paper');
canvas.setHeight(500);
canvas.setWidth(700);

const pageData = { 
	y: 50,  
  x: 50,
  width: 300,
  height: 100,
  paragraphMarginBottom: 20
};

const page = new fabric.Rect({
  left: pageData.x,
  top: pageData.y,
  width: pageData.width,
  height: pageData.height,
  fill: 'red',
  originX: 'left',
  originY: 'top',
//  originX: 'left',
//  originY: 'top',
});



const paragraphOne = new fabric.Textbox('This is the first paragraph text aligned left.', {
  left: pageData.x,
  width: pageData.width,
  top: pageData.y,
  clipTo: function(ctx){
  	ctx.rect(
    -pageData.width / 2,
		-pageData.height / 2,
    pageData.width,
    pageData.height);
  }
//  originX: 'left',
 // originY: 'top',
});

const paragraphTwo = new fabric.Textbox('This is the second paragraph text aligned right.', {
  width: pageData.width,
  textAlign:'right',
//  originX: 'left',
//  originY: 'top',
  top: pageData.y + paragraphOne.height + pageData.paragraphMarginBottom
});


canvas.add(page, paragraphOne);


page.on('__scaling', function(){
  const width = this.getScaledWidth();
  const height = this.getScaledHeight();
  
	this.scale(1);
  this.set({
    width,
    height
  });
  
	this.setCoords();
	canvas.renderAll();
  
  const paragraphs = page.getObjects();
  let newTop = this.top - this.height / 2;
  let newPageHeight = 0;
  paragraphs.forEach((p)=>{
    p.scale(1);
    p.set({
      left: -width / 2,
      width,
      top: newTop
    });
    
    newTop += p.height + pageData.paragraphMarginBottom;
    newPageHeight += p.height + pageData.paragraphMarginBottom;
  });
  this.set({
    height: newPageHeight
  });
//  this.setCoords();
  canvas.renderAll();
});

canvas.renderAll();