fiscme fiscme - 7 months ago 79
Javascript Question

Create spots or strips pattern in Fabric.js

I want to fill a polygon with a pattern of spots or stripes.
I can find plenty of examples using an image as a pattern but not other shapes or polygons

Also in http://fabricjs.com/dynamic-patterns/ when you adjust the angle of the pattern it does it from the top left corner of the image/canvas .. Any way to do it from the centre of the canvas (so the pug rotates around the centre and doesn't get cut off)

Answer

I can find plenty of examples using an image as a pattern but not other shapes or polygons.

Using that same dynamic patterns demo, you would just need to replace:

patternSourceCanvas.add(img);

with:

patternSourceCanvas.add(yourShape);

..making sure that canvas has proper dimensions. As you can see, Fabric can use entire in-memory canvas to render a pattern, so anything you add onto that canvas (including SVG shapes or simple shapes or whatever) will be used as a pattern.

.. when you adjust the angle of the pattern it does it from the top left corner of the image/canvas

If you change originX/originY to "center", the images of pug should rotate around their centers:

img.scaleToWidth(100).set({
  originX: 'center',
  originY: 'center'
});