Fabricjs Textbox make the text shrink to fit

后端 未结 1 834
梦如初夏
梦如初夏 2020-12-14 18:44

I would define a text box (single-line)

By default, with a character size of 16 (for example)

When the text gets bigger than the text box, I do not want it t

相关标签:
1条回答
  • 2020-12-14 19:23

    This is a basic fiddle that can replicate your idea. The point is that you have an event that fires on every text change and that can be used to do something before the textbox is rendered.

    In this case i m shrinking font size based on a non standard parameter i added to textbox called fixedWidth

    // 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
    });
    
    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;
      }
    });
    
    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>

    0 讨论(0)
提交回复
热议问题