Skip to content

Instantly share code, notes, and snippets.

@howtomakeaturn
Last active March 22, 2022 07:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save howtomakeaturn/4855a886363085d3067f2f3cbbf36c72 to your computer and use it in GitHub Desktop.
Save howtomakeaturn/4855a886363085d3067f2f3cbbf36c72 to your computer and use it in GitHub Desktop.
fabricjs-TextboxWithPadding.md

create the new type

fabric.TextboxWithPadding = fabric.util.createClass(fabric.Textbox, {
  type: 'textboxwithpadding',

  toObject: function() {
    return fabric.util.object.extend(this.callSuper('toObject'), {
      backgroundColor: this.get('backgroundColor'),
      padding: this.get('padding'),
    });
  },

  _renderBackground: function(ctx) {
    if (!this.backgroundColor) {
      return;
    }
    var dim = this._getNonTransformedDimensions();
    ctx.fillStyle = this.backgroundColor;

    ctx.fillRect(
      -dim.x / 2 - this.padding,
      -dim.y / 2 - this.padding,
      dim.x + this.padding * 2,
      dim.y + this.padding * 2
    );
    // if there is background color no other shadows
    // should be casted
    this._removeShadow(ctx);
  }
});

use the new type

var t2 = new fabric.TextboxWithPadding('This is a Textbox', {
  textAlign: 'center',
  top: 200,
  left: 100,
  width: 400,
  fontSize: 50,
  fontWeight: 'bold',
  fill: 'black',
  stroke: 'white',
  paintFirst: 'stroke',
  strokeWidth: 3,
  backgroundColor: 'yellow',
  padding: 20,
});

canvas.add(t2);
@usama-gh
Copy link

Doesn't work when you export it as a JSON and loads it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment