如何固定textBox的大小,以防止其在键入时溢出(固定的宽度和高度)?
var canvas = window._canvas = new fabric.Canvas('c');
var text = new fabric.Textbox('MyText', {
width: 300,
height: 300,
top: 5,
left: 5,
hasControls: false,
fontSize: 30,
fixedWidth: 300,
fixedFontSize: 30
});
canvas.add(text);http://jsfiddle.net/643qazk0/2/
发布于 2017-11-13 21:19:02
您可以重写insertChars方法并检查文本溢出。
请参阅下面的代码片段。
// Create canvas
const canvas = new fabric.Canvas(document.querySelector('canvas'));
// Define `LimitedTextbox` class which extends `Textbox`
const LimitedTextbox = fabric.util.createClass(fabric.Textbox, {
// Override `insertChars` method
insertChars: function(chars) {
if (this.maxWidth) {
const textWidthUnderCursor = this._getLineWidth(this.ctx, this.get2DCursorLocation().lineIndex);
if (textWidthUnderCursor + this.ctx.measureText(chars).width > this.maxWidth) {
chars = '\n' + chars;
}
}
if (this.maxLines) {
const newLinesLength = this._wrapText(this.ctx, this.text + chars).length;
if (newLinesLength > this.maxLines) {
return;
}
}
// Call parent class method
this.callSuper('insertChars', chars);
}
});
// Create limited text box with max width 300px and max 2 lines
canvas.add(
new LimitedTextbox('text', {
top: 10,
left: 10,
width: 300,
maxWidth: 300,
maxLines: 2
})
);
canvas.renderAll();.canvas-container {
border: 1px solid gray;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>
<canvas width="600" height="300"></canvas>
使用Fabric 1.7.20进行测试
发布于 2019-12-16 21:31:15
对于fabric js版本2+中的固定文本框,我们需要覆盖onInput函数,如下所示
onInput: function(e) {
if(this.width > this.maxWidth) {
return;
}
if((this._textLines.length) > this.maxLines) {
return;
}
// Call parent class method
this.callSuper('onInput', e);
}注意: maxWidth -限制宽度,maxLines -限制文本框中的高度/行数
发布于 2021-03-30 19:10:34
该解决方案仅提供了字符的表示的here块。在引擎盖下,隐藏的文本区继续接受字符。
因此,如果允许并单击退格键-所有在maxLines之后编写的不可见文本都将弹出。
Solution:使用以下代码将隐藏文本区域与文本同步:
if (this._textLines.length > this.maxLines && e.inputType !== 'deleteContentBackward') {
this.hiddenTextarea.value = this.text;
return;
}https://stackoverflow.com/questions/45711558
复制相似问题