在Fabric.js中调整基于文本的对象的大小时,如何防止包含文本的垂直和水平拉伸?

问题描述 投票:1回答:1

我希望能够缩放基于文本的对象(例如,使用IText,Textbox的类和子类),而无需在对象内部扩展文本。缩放和移动的交互是在用户端(UI)上,而不是以编程方式进行的(我正在使用图形编辑器)。

enter image description here

我正在寻找的行为类似于即时贴应用程序中的行为:您可以缩放纸张,但是此操作也不能缩放您的文本。

我已经检查过,但这仅用于水平预防:Fabric.js How to resize IText horizontally without stretching the text

这都不是我想要/想要的:Fabric.js : How to set a custom size to Text or IText?

我知道缩放系数不等于1表示内部文本的拉伸,并且通过更改widthheight我可以在不缩放文本的情况下调整对象的大小,因此我尝试使用事件监听器。

我尝试了IText,Textbox的许多组合以及一些缩放事件,例如这样:

fbtext.on('scaling', function() {
                      this.set({
                        width : this.width  * this.scaleX,
                        height: this.height * this.scaleY,
                        scaleX: 1,
                        scaleY: 1,
                      });
                    });

我也在Textbox中尝试过此方法:

fbtext.on('scaling', function() {
                      this.set({
                        height: this.height * this.scaleY,
                      });
                    });

但是到目前为止,没有任何效果。我没有主意。

javascript html5-canvas fabricjs draw
1个回答
0
投票

var canvas = new fabric.Canvas('mycanvas');

let textbox = new fabric.Textbox("Sample text", {
   left: 100,
   top: 100
});

let lastHeight;

const updateTextSize = () => {	

  const controlPoint = textbox.__corner;

  //mr and ml are the only controlPoints that dont modify textbox height
  if( controlPoint && controlPoint != "mr" && controlPoint != "ml"){
 	   lastHeight =  textbox.height * textbox.scaleY;			
  }

  textbox.set({		
  	 height: lastHeight || textbox.height,
	 scaleY:1				
  });
  
  canvas.renderAll();
};
		
	
textbox.on('scaling', updateTextSize );
textbox.on('editing:entered', updateTextSize);
canvas.on('text:changed', updateTextSize);
  
canvas.add(textbox);
canvas {
    border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.3.2/fabric.min.js"></script>
<canvas id="mycanvas" width="400" height="400"></canvas>

这里是一个代码示例,可让您修改“便签大小”而不会拉长文本

© www.soinside.com 2019 - 2024. All rights reserved.