Как привязать высоту текста к ограничительной рамке в текстовом поле fabricJS - PullRequest
0 голосов
/ 24 июня 2019

https://imgur.com/a/M1PpTiH

Так что я работаю с текстовыми полями fabricjs, и у меня есть пользовательская реализация, которая позволяет обтекание текстом, в то же время позволяя пользователю регулировать высоту ограничительной рамки.проблема в том, что скрытый ограничивающий прямоугольник для самого текста не совпадает с визуально перетаскиваемым полем объекта (см. ссылку выше, например).Кажется, он масштабируется только на 50% от того, насколько я уменьшу размер коробки.Моя цель состоит в том, чтобы вертикальное переполнение текста просто не показывалось за пределами ограничительной рамки.Это происходит как есть, но с неправильным масштабированием не совпадает, как я сказал.так как я могу получить значение этого скрытого ящика для соответствия видимому ограничивающему ящику?

http://jsfiddle.net/L3xh06c5/

Вот скрипка с реализацией пользовательского объекта, с которой я работаю

// initialize fabric canvas and assign to global windows object for debug
this.canvas = new fabric.Canvas("c", {
                                        selection: false,
                                        backgroundColor: '#fff',
                                        preserveObjectStacking: true,
                                        uniScaleTransform: true, });


fabric.ClueTextbox = fabric.util.createClass(fabric.Textbox, {
        type: 'cluetextbox',
         /**
         * Properties which when set cause object to change dimensions
         * @type Object
         * @private
         */
        _dimensionAffectingProps: 
fabric.IText.prototype._dimensionAffectingProps.slice(0),
    });

    var newItem = new fabric.ClueTextbox("Clue Text will appear here, with the same properties as this display text, bounded by this box... Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eget mauris in eros efficitur sodales vel eu lectus. Curabitur dui felis, posuere non urna at, rhoncus efficitur ipsum.")
            newItem.set({
                fontSize: 40,
                lineHeight: 1,
                charSpacing: 10,
                editable: false,
                lockUniScaling: false,
                lockScalingFlip: true,
            });
            newItem.setControlsVisibility({
                mt: false, // middle top disable
                mb: false, // midle bottom
                ml: false, // middle left
                mr: false, // middle right
            });
            newItem.on('scaling',  () => {
                var newHeight = newItem.height * newItem.scaleY;
                newItem.set({
                    width: newItem.width * newItem.scaleX,
                    scaleX: 1,
                });
                newItem.initDimensions();
                newItem.set({ height: newHeight, scaleY: 1 })
            });

             this.canvas.add(newItem);

// ДОБАВИТЬ ВАШ КОД ЗДЕСЬ

1 Ответ

1 голос
/ 25 июня 2019

Вот решение. Я переписываю _renderTextCommon

/**
 * fabric.js template for bug reports
 *
 * Please update the name of the jsfiddle (see Fiddle Options).
 * This templates uses latest dev verison of fabric.js (https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js).
 */

// initialize fabric canvas and assign to global windows object for debug
this.canvas = new fabric.Canvas("c", {
                                            selection: false,
                                            backgroundColor: '#fff',
                                            preserveObjectStacking: true,
                                            uniScaleTransform: true, });


fabric.ClueTextbox = fabric.util.createClass(fabric.Textbox, {
            type: 'cluetextbox',
             /**
             * Properties which when set cause object to change dimensions
             * @type Object
             * @private
             */
            _dimensionAffectingProps: fabric.IText.prototype._dimensionAffectingProps.slice(0),
            
            _renderTextCommon: function(ctx, method) {
                ctx.save();
                var lineHeights = 0, left = this._getLeftOffset(), top = this._getTopOffset(),
                    offsets = this._applyPatternGradientTransform(ctx, method === 'fillText' ? this.fill : 							this.stroke);
                for (var i = 0, len = this._textLines.length; i < len; i++) {
                  var heightOfLine = this.getHeightOfLine(i),
                      maxHeight = heightOfLine / this.lineHeight,
                      leftOffset = this._getLineLeftOffset(i);
                  if(lineHeights+heightOfLine < this.getScaledHeight()){
                  this._renderTextLine(
                    method,
                    ctx,
                    this._textLines[i],
                    left + leftOffset - offsets.offsetX,
                    top + lineHeights + maxHeight - offsets.offsetY,
                    i
                  );
                  }
                  lineHeights += heightOfLine;
                }
                ctx.restore();
              }
        });
        
        var newItem = new fabric.ClueTextbox("Clue Text will appear here, ")
                newItem.set({
                    fontSize: 40,
                    lineHeight: 1,
                    charSpacing: 10,
                    editable: false,
                    dirty:false,
                    objectCaching:false,
                    lockUniScaling: false,
                    lockScalingFlip: true,
                });
                newItem.setControlsVisibility({
                    mt: false, // middle top disable
                    mb: false, // midle bottom
                    ml: false, // middle left
                    mr: false, // middle right
                });
                newItem.on('scaling',  () => {
                    var newHeight = newItem.height * newItem.scaleY;
                    newItem.set({
                        width: newItem.width * newItem.scaleX,
                        scaleX: 1,
                    });
                    newItem.initDimensions();
                    newItem.set({ height: newHeight, scaleY: 1 })
                });
                
                 this.canvas.add(newItem);
// ADD YOUR CODE HERE
canvas {
    border: 1px solid #999;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="600" height="600"></canvas>
...