Pattern Repeat on Object Scaling in fabric JS

2.5k views Asked by At
Is there any way to repeat the pattern inside an object in fabric JS.

Suppose i have a rectangle filled with a pattern. I want the pattern to be repeated when i scale the rectangle.

Right now it is zooming when i scale it.

Thanks

1

There are 1 answers

0
Riz On

@user2571818 I was also looking for this and finally got it working. We'll have to use object:scaling event to scale the object back to 1x and change size of the object instead to make the pattern repeat instead of scaling it. See it here

var canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;

  var padding = 0;

  fabric.Image.fromURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAASdEVYdFNvZnR3YXJlAEdyZWVuc2hvdF5VCAUAAADLSURBVFhH7ZnBCoMwEET9/68URBHSNj0UolFoI+aQickKlT05jz0MGQIPkb2kadu3ta42ff/MTtLRazct55bajOMjO0lHr920vnWMMTGV0GuphVALoRaiqNV1dq4TLsdUIrTe+z0fw+ndmEo0w/D61AmXYyqh1179WjGVuNLyl0eohVALuZ8Wtzwgt9zyiNxSC6EWQi1EUYtbHpBbbnlEbqmFUAuhFqKoxS0PyC23PCK31EKohVAL0dXK3vLSOX0TnKZ1z8fw/3uiW37L27QIZwrV4gAAAABJRU5ErkJggg==', function(img) {

    img.scaleToWidth(50);
    var patternSourceCanvas = new fabric.StaticCanvas();
    patternSourceCanvas.add(img);
    patternSourceCanvas.renderAll();
    var pattern = new fabric.Pattern({
      source: function() {
        patternSourceCanvas.setDimensions({
          width: img.getScaledWidth() + padding,
          height: img.getScaledHeight() + padding
        });
        patternSourceCanvas.renderAll();
        return patternSourceCanvas.getElement();
      },
      repeat: 'repeat'
    }); 

    var rect = new fabric.Rect({
        width: 250,
        height: 250,
        fill: pattern,
        objectCaching: false
    });

    canvas.add(rect);
    rect.center().setCoords();

 });



canvas.on('object:scaling', function(e) {
  if (e.target != null) {
    console.log(e.target);
    var obj = e.target;
        var height = obj.height * obj.scaleY;
        var width = obj.width * obj.scaleX;
        obj.height = height;
        obj.width = width;
        obj.scaleX = 1;
        obj.scaleY = 1;
  }
});

JSFiddle: https://jsfiddle.net/dotriz/ajsdmg4s/