微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Konva js文本转换比例为字体大小

如何解决Konva js文本转换比例为字体大小

我希望获得与使用转换器缩放文本相同的结果,但是更改fontSize不能缩放。

那是在拖动变压器锚点时更改字体大小,宽度,高度等,我的文本看起来像是缩放的。

有人可以帮我吗?

解决方法

我认为这可能是保持缩放后的文本看起来不错。默认的转换器允许用户分别拉伸宽度和高度,从而创建难看的文本。

为了使用变形器保持外观精美的文本,我们需要进行制作,以使变形器尊重文本形状的比例。

为此,请使用转换器的enabledAnchors属性关闭宽度和高度拖动锚,然后设置

transformer.keepRatio(true);

在下面的代码段中尝试。

[EDIT]我修改了代码段以支持原始问题的目的,即以与转换器产生的内容匹配的100%大小的文本替换转换后的文本。请参阅simpleText.on('transformend'...)侦听器。

请注意,由于内部字体提示可能会发生变化(例如,字符间),因此通过转换器v替换新的计算出的字体大小来缩放字体时,您可能会看到的完全不一致特定字体大小上方/下方的间距。

我的钱仍然是花在使变压器保持比率上,因为这是最可靠的解决方案,而且几乎免费。但是该代码段包含一种实现您最初所说的意图的方法。

// Set up the canvas and shapes
let stage = new Konva.Stage({container: 'container1',width: $('#container1').width(),height: $('#container1').height()});
let layer = new Konva.Layer({draggable: false});
stage.add(layer);

// Add a transformer - note we use enabledAnchors to ensure no height0onlly or width-only anchors are used as these do not respect the ratio.
let transFormer1 = new Konva.Transformer({
        enabledAnchors: [
          'top-left','top-right','bottom-left','bottom-right',]
  });
transFormer1.keepRatio(true); // ** Tell the transformer to maintain aspect ratio **

layer.add(transFormer1);

var simpleText = new Konva.Text({
  x: 40,y: 65,text: 'Bart,with 10,000 dollars we`d be millionaires!',fontSize: 36,fontFamily: 'Calibri',fill: 'cyan',});

// When the transform ends we set the new font size and reset the scale to 1.
simpleText.on('transformend',function () {
  console.log('transform end - before reset font size = ' + this.fontSize() + ' at scale ' + this.scaleX());
  this.fontSize(this.fontSize() * this.scaleX());
  this.scale({x: 1,y: 1});
  layer.batchDraw();
  console.log('transform end - after reset font size = ' + this.fontSize() + ' at scale ' + this.scaleX());
});

layer.add(simpleText);
transFormer1.nodes([simpleText])

stage.draw();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/konva@7.1.1/konva.min.js"></script> 
<p>Resize the text - note the aspect ratio is retained.
</p>
<div id='container1' style="height: 200px; background-color: silver; overflow: hidden; position: relative;"></div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。