简体   繁体   中英

Fabric.js - how to create TextBox without line breaks?

I was searching a lot for properties like maxLines , noWrap , splitByWhitespace , etc. in Fabric.js documentation, but they don't exist. Do you know a working solution to disable text wrapping inside fabric.Textbox ?

my code:

const text = new window.fabric.Textbox('expected single line', {
  fontFamily: 'Nunito Sans',
  fontWeight: 400,
  fontSize: 15,
  originX: 'center',
  originY: 'center',
});

const border = new window.fabric.Rect({
  rx: 10,
  ry: 10,
  fill: '#999999',
  height: text.height + 10,
  width: text.width + 100,
  originX: 'center',
  originY: 'center',
});

const group = new window.fabric.Group([border, text], {
  originX: 'left',
  originY: 'top',
  hasRotatingPoint: false,
  height: 42,
  width: 200,
  top: 167,
  left: 50,
});
canvas.add(group);

actual result demo:

多行文本框

as you can see there are line breaks on every whitespace, but I want to have a single-line text with spaces. interestingly, if I replace whitespaces with underscore _ , I get one-line text.

demo:

单行文本框

I don't know about disabling wrapping in the Textbox .
But to get a one-line text, you can

  • either set the Textbox width
  • or use Text instead of Textview (see this codepen )

originally found here: https://stackoverflow.com/a/41335051/1815624

this sorta does what you want by checking the add values of fixedWidth and fixedHeight then checking those compared to the new width after changing the text...

this is not really a solution but it may help you figure something out...

 // ADD YOUR CODE HERE var canvas = new fabric.Canvas('c'); var t1 = new fabric.Textbox('MyText', { width: 150, top: 5, left: 5, fontSize: 16, textAlign: 'center', fixedWidth: 150, fixedHeight: 20, }); canvas.on('text:changed', function(opt) { var t1 = opt.target; if (t1.width > t1.fixedWidth) { t1.fontSize *= t1.fixedWidth / (t1.width + 1); t1.width = t1.fixedWidth; } if(t1.height > t1.fixedHeight){ t1.fontSize *= t1.fixedHeight / (t1.height + 1); t1.height = t1.fixedHeight; } canvas.renderAll(); }); canvas.add(t1);
 canvas { border: 1px solid #999; }
 <script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script> <canvas id="c" width="600" height="600"></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM