How to scale a pattern before fill in fabricjs

3k views Asked by At

I'm trying to fill a polygon with a pattern that is larger than the polygon itself. I want to scale down the pattern before filling the polygon with it but I can't figure out how. I can certainly resize the file pattern file before it's loaded but I was wondering if I could do that directly in fabricjs.

Here's what I'm trying:

var leftStickPoints = [{x: 0, y: 0},{x: 86, y: 86},{x: 86, y: 441},{x: 0, y: 528}];
var leftStick = new fabric.Polygon(leftStickPoints, {
    left: 20,
    top: 20,
    fill: 'orange',
});
canvas.add(leftStick);

fabric.util.loadImage(patternURL, function (img) {
    // ------
    // pattern scale down should happen here I think but I cannot figure out how to manipulate the `img` param in order to do so
    // ------
    leftStick.fill = new fabric.Pattern({
        source: img,
        repeat: 'repeat-y'
    });
    canvas.renderAll();
});

Any ideas how to scale the pattern before apply it?

Thanks!

1

There are 1 answers

1
Nistor Cristian On BEST ANSWER

I made you a jsFiddle based on http://fabricjs.com/dynamic-patterns/ example. You can scale the image to a certain width from img.scaleToWidth(200);. You can now use this to accomplish what you need.