Michael Tsipes
Michael Tsipes

Reputation: 71

Fabric.js. Dynamic Pattern not working

A little bit frustrated here. I am trying to get dynamic patterns work as it shown on demo here http://fabricjs.com/dynamic-patterns.

I wrote function but it won't change pattern size once t is created.

I tried to assign img object to window array and change sizes and even inserted rescale operation at the end of the function, but my pattern still won't change its size.

I know i'm doing something wrong, but i cannot figure what. Maybe it is Fabric.js version or canvas.requestRenderAll();

Please, let me know if you have any idea on how to deal with this problem.

Here is the code.

        'setBackgroundItem':function(){

        fabric.Image.fromURL(arr.image, function(img) {

            var patternSourceCanvas = new fabric.StaticCanvas();

            var to_set_width = canvas.getActiveObject().width; // avtorkoda

            img.set({opacity: 0.9});
            img.scaleToWidth(to_set_width);

            w.fills.push(img);

            patternSourceCanvas.add(img);
            patternSourceCanvas.setDimensions({
                width: to_set_width,// на ноуте клиента работает с этим. у меня без может)
                height: Math.floor(to_set_width)
            });


            var texture = patternSourceCanvas.getElement();

            var pattern = new fabric.Pattern({
                source: texture,
                repeat: 'no-repeat',
                offsetX: 0,
                offsetY: 0
            });

            var activeObject =  canvas.getActiveObject();
            var activeGroup  =  canvas.getActiveGroup();

            activeObject.setFill(pattern);


            img.scaleToHeight(40);

            canvas.renderAll();
        });
    }, 

Thanks in advance.

Upvotes: 0

Views: 958

Answers (1)

Cooble
Cooble

Reputation: 57

A bit late to the party:

The documentation doesn't specify this, but in order to change the pattern width after you've applied it, you must disable caching on the object that the pattern was applied upon.

In your case:

activeObject.set('objectCaching', false);

Another place where it can be observed (from FabricJS's own example here):

canvas.add(new fabric.Polygon([
  {x: 185, y: 0},
  {x: 250, y: 100},
  {x: 385, y: 170},
  {x: 0, y: 245} ], {
    left: 0,
    top: 200,
    angle: -30,
    fill: pattern,
    objectCaching: false
  }));

You either do it like this, or you can make objectCaching false as a default for all the objects (not recommeded for heavy projects)

Upvotes: 0

Related Questions